Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMock:: [java.lang.IllegalStateException: no last call on a mock available]

To mock a static method powermock giving an exception while expect().

@Test
public void testRegistrarService()
{
   mockStatic(IdGenerator.class);
   expect(IdGenerator.generateNewId()).andReturn(42L);
   long actualId=serTestObj.registerService();
   replay(IdGenerator.class);
   verify(IdGenerator.class);
   assertEquals(42L,actualId);
 }


public class ServiceRegistrator
{
public long registerService()
{
    long id = IdGenerator.generateNewId();
    return id;
 }
}

public class IdGenerator
{
  public static long generateNewId()
  {
    return System.currentTimeMillis();
  }
}

Exception is:

java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:521)
at org.easymock.EasyMock.expect(EasyMock.java:499)
at  home.powermock.testServiceRegistrator.testRegistrarService(testServiceRegistrator.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at com.intellij.rt.execution.junit2.JUnitStarter.main(JUnitStarter.java:31)

how to mock staic method,while m using powerMock i'm using intelliJ idea,how to resolve that exception.

like image 365
SachG Avatar asked Dec 01 '25 11:12

SachG


1 Answers

Your code is missing the annotation

@PrepareForTest(IdGenerator.class)
like image 141
JoseK Avatar answered Dec 03 '25 02:12

JoseK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!