Wednesday, July 17, 2013

java.lang.illegalstateexception: missing behavior definition for the preceding method call

I have the following exception while mocking a final method with PowerMock.

java.lang.illegalStateException: missing behavior definition for the preceding method call


My previous code was:


 ReloadableResourceBundleMessageSource mockMessage =
createMock(ReloadableResourceBundleMessageSource.class);
        expect(mockMessage.getMessage("text",
null, Locale.ENGLISH)).andReturn("error_message");
 replay(mockMessage);


Then I realized that createMock() and replay() belongs to EasyMock not PowerMock.
I explicitly did these calls:

 ReloadableResourceBundleMessageSource mockMessage =
PowerMock.createMock(ReloadableResourceBundleMessageSource .class);
        expect(mockMessage.getMessage("text",
null, Locale.ENGLISH)).andReturn("error_message");
        PowerMock.replay(mockMessage);


But that's not enough. For PowerMock to work, you'll also need to add few annotations before the class definition.


@RunWith(PowerMockRunner.class)
@PrepareForTest(ReloadableResourceBundleMessageSource.class)

Notice that @PrepareForTest can also be defined just before the test method.
After these fixes my test begins to work.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete