Mocking Statics and java.lang.IllegalStateException: no last call on a mock available

If you use PowerMock to mock a static object e.g.

mockStatic(FacesContext.class)

and encounter the following error:

java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:174)
at org.easymock.EasyMock.expect(EasyMock.java:156)

Check that you have prepared the Class for test using the @PrepareForTest annotation.

e.g.

@RunWith(PowerMockRunner.class)
@PrepareForTest(
{
	FacesContext.class
})
public class ....

An excellent article discussing mocking statics by one of the PowerMock developers can be found here: http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/

Note that you also need to @PrepareForTest any classes where you are expecting a private method call with expectPrivate.  If you don’t, your test execution will try and go into the private method and actually run all the code. The @PrepareForTest annotation can either go at the method level as shown in the example below, or at the class level as shown in the example posted above.

@PrepareForTest(ClassUnderTest.class)
@Test
public void testNext() throws Exception
{
	String privateMethod = "isNextEnabled";
	ClassUnderTest partMock = createPartialMock(ClassUnderTest.class, privateMethod);
	expectPrivate(partMock, privateMethod).andReturn(true);
	replayAll();
	partMock.next();
	verifyAll();
}
You can leave a response, or trackback from your own site.

Leave a Reply