我正在尝试模拟一个类的私有方法。
我想为下面的类模拟isBalancedTree方法。
public class DummyClassForPowerMockTest {
public boolean isBalancedTree_1() {
System.out.println("Inside isBalancedTree_1");
return isBalancedTree("hello");
}
private boolean isBalancedTree(String a) {
System.out.println("Inside the isBalancedTree");
return false;
}
}
以下是测试代码。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:spring-configuration/unit-testing-config.xml" })
@PrepareForTest(DummyClassForPowerMockTest.class)
public class PowerMockTest {
final String methodToTest = "isBalancedTree";
@Resource(name = "notify")
private DummyClassForPowerMockTest notify;
@Rule
public PowerMockRule rule = new PowerMockRule();
@Before
public void initialize(){
PowerMock.resetAll();
}
@Test
public void testA() throws Exception{
PowerMock.expectPrivate(notify, methodToTest, EasyMock.anyObject(String.class)).andReturn(true).anyTimes();
PowerMock.replayAll();
boolean result = notify.isBalancedTree_1();
Assert.assertEquals(true, result);
PowerMock.verifyAll();
}
}
我从Spring开始为DummyClassForPowerMockTest创建bean
public class PowerMockCreatePartialMockFactoryBean<T> implements FactoryBean<T> {
private Class<T> classToMock;
private String methodToMock;
public PowerMockCreatePartialMockFactoryBean(Class<T> classToMock, String methodName) {
this.classToMock = classToMock;
this.methodToMock = methodName;
System.out.println("Inside the power mock create partial constructor .. "+methodToMock);
}
@Override
public T getObject() throws Exception {
System.out.println("Inside the getObject method ........ "+methodToMock);
return PowerMock.createPartialMock(classToMock, methodToMock);
}
@Override
public Class<T> getObjectType() {
return classToMock;
}
@Override
public boolean isSingleton() {
return true;
}
}
使用以下bean。
<bean id="notify" class="PowerMockCreatePartialMockFactoryBean">
<constructor-arg index="0" value="DummyClassForPowerMockTest" />
<constructor-arg index="1" value="isBalancedTree"/>
</bean>
有了这个,我收到以下错误。
[junit] Testcase: testA took 3.24 sec
[junit] Caused an ERROR
[junit] no last call on a mock available
[junit] java.lang.IllegalStateException: no last call on a mock available
[junit] at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:520)
[junit] at org.easymock.EasyMock.expectLastCall(EasyMock.java:511)
[junit] at org.powermock.api.easymock.PowerMock.doExpectPrivate(PowerMock.java:2248)
[junit] at org.powermock.api.easymock.PowerMock.expectPrivate(PowerMock.java:1400)
[junit] at org.powermock.api.easymock.PowerMock.expectPrivate(PowerMock.java:1411)
[junit] at org.powermock.api.easymock.PowerMock.expectPrivate(PowerMock.java:1357)
我不确定为什么会出现这个错误。我在网上搜索了很多这个错误,但没有任何帮助。当我没有用bean初始化类时,我能够成功运行测试。但是当我尝试注入一个bean时,它失败并出现上述错误。有人可以帮我解决这个问题。
提前致谢。