我有以下项目的调用链
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();
}
}
请帮助
答案 0 :(得分:2)
试试这个
Proxy regProxy = PowerMock.createNiceMock(Proxy.class);
当您在链式方法中执行EasyMock.createMock()
时,它会失败,因为Easymock无法识别此方法将在其他地方被调用,但是当我们执行EasyMock.createNiceMock()
时,模拟不会因此意外而失败方法,并且可以根据需要执行模拟。
事实上,我已经习惯了这个错误,比如一周,当我发现这个解决方法时,这就像是一种祝福。
希望这有帮助! 祝你好运!