我的项目有以下调用链
Impl.execute() --> Helper.help() --> Proxy.doOperation()
我正在尝试在 PowerMock 和 TestNG 中执行 Impl.execute() 的测试用例。我遇到以下异常
execute(ImplTest) Time elapsed: 0.391 sec <<< FAILURE!
java.lang.AssertionError:
Unexpected method call Proxy.doOperation({clientId=123456}, ""):
Proxy.doOperation({}, null): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:85)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:94)
at com.xxx.xxx.xxx.sync.services.Proxy$$EnhancerByCGLIB$$1937be76.doOperation(<generated>)
at com.xxx.xxx.xxx.sync.services.helper.Helper.getIdFromClient(Helper.java:39)
at com.xxx.xxx.xxx.sync.services.impl.Impl.execute(Impl.java:97)
at com.xxx.xxx.xxx.sync.services.impl.ImplTest.execute(ImplTest.java:130)
我写了下面的代码
@PrepareForTest({ApplicationContextLoader.class,Helper.class})
@PowerMockIgnore({"javax.management.*", "javax.xml.*","org.xml.*","org.w3c.dom.*"})
public class ImplTest extends PowerMockTestCase {
@ObjectFactory
/**
* Configure TestNG to use the PowerMock object factory.
*/
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
@Test
public void execute() {
Impl impl = new Impl();
Proxy regProxy = PowerMock.createMock(Proxy.class);
PowerMock.expectNew(Proxy.class).andReturn(regProxy);
expect(regProxy.doOperation(Matchers.anyMap(),Matchers.any(String.class))).andReturn(someString);
PowerMock.replayAll();
Assert.assertEquals(impl.execute(request, ""),"");
PowerMock.verifyAll();
}
}
请帮忙
最佳答案
试试这个
Proxy regProxy = PowerMock.createNiceMock(Proxy.class);
当您在链式方法中执行 EasyMock.createMock()
时,它会失败,因为 Easymock 无法识别该方法将在其他地方调用,但是当我们执行 EasyMock.createNiceMock 时()
在这个意外的方法上,模拟不会失败,并且可以按照我们想要的方式执行模拟。
事实上,我花了大约一周的时间来解决这个错误,当我找到这个解决方法时,这就像是一种祝福。
希望这有帮助! 祝你好运!
关于java - powermock 中意外的方法调用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27487592/