【发布时间】:2015-08-25 15:49:49
【问题描述】:
我(仍在)尝试使用 PowerMockito 检查bar(Alpha, Baz) 是否调用了bar(Xray, Baz)(因为bar(Xray, Baz) 是private) - 没有实际调用后者,因为我的MCVE 类Foo 在下面。 (我上过同一个课程earlier,Foo 中的所有方法都是public - 以防你有似曾相识的感觉......)
public class Foo {
private String bar(Xray xray, Baz baz) {
return "Xray";
}
private String bar(Zulu zulu, Baz baz) {
return "Zulu";
}
public String bar(Alpha alpha, Baz baz) {
if(alpha.get() instanceof Xray) {
return bar((Xray)alpha.get(), baz);
} else if(alpha.get() instanceof Zulu) {
return bar((Zulu)alpha.get(), baz);
} else {
return null;
}
}
}
当我尝试运行下面的测试时,我从 PowerMock 获得了 NPE:
@RunWith(PowerMockRunner.class)
// @PrepareOnlyThisForTest(Foo.class) // we aren't looking at the byte code, I think
public class FooTest {
@Test
public void testBar_callsBarWithXray() throws Exception {
Baz baz = new Baz(); //POJOs
Alpha alpha = new Alpha();
alpha.set(new Xray());
Foo foo = new Foo();
Foo stub = spy(foo); // using Mockito, as it's neither final nor "not spyable"
// NPE at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:67)
PowerMockito.doReturn("ok").when(stub, "bar", Xray.class, Baz.class);
stub.bar(alpha, baz);
// Testing if bar(Xray, Baz) was called by bar(Alpha, Baz)
PowerMockito.verifyPrivate(foo).invoke("bar", Xray.class, Baz.class);
// Mockito's equivalent for a public method: verify(stub, times(1)).bar(any(Xray.class), any(Baz.class));
}
}
如果我将存根设为PowerMockito.spy(foo),我会得到一个IllegalArgumentException: argument type mismatch at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:2014)。 (它与 NPE 在同一条线上冒泡。)
我正在使用 Mockito-core 1.9.5、PowerMock 1.5.4(module-junit4 和 api-mockito)和 JUnit 4.11。
我需要改变什么来阻止异常被抛出?我怎样才能使这个测试工作? (除了testing that 我的班级工作,而不是如何...;-))
【问题讨论】:
标签: java powermock overloading private-members powermockito