我正试图使用Powermock编写一个TestNg测试来模拟静态函数调用。我的测试代码是:
import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.verify;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.Assert;
import org.testng.annotations.Test;
@PrepareForTest(TestStringProvider.class)
public class TryPowerMock {
public void test() {
String string = TestStringProvider.getString();
Assert.assertEquals(string, "testString");
}
@Test
public void tryPowerMock() {
mockStatic(TestStringProvider.class);
expect(TestStringProvider.getString()).andReturn("testString");
replay(TestStringProvider.class);
test();
verify(TestStringProvider.class);
}
}
具有静态功能的类:
public class TestStringProvider {
public static String getString(){
return "WHY AM I CALLED, I AM SUPPOSED TO BE MOCKED";
}
}
运行此测试会给我以下异常,
FAILED: tryPowerMock
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:520)
at org.easymock.EasyMock.expect(EasyMock.java:498)
at com.archit.learn.powermock.TryPowerMock.tryPowerMock(TryPowerMock.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
进一步探索并自己找到了解决方案。
我不得不从类PowerMockTestCase 扩展我的单元测试