现在是系列的第 3 部分...
我(仍在)尝试检查是否使用 PowerMockito ( is )bar(Alpha, Baz)
调用- 没有实际调用后者,因为我在下面的 MCVE 类。请注意,没有返回任何内容,而其他两个返回,并且我知道我应该测试Foo 是否有效,而不是如何...bar(Xray, Baz)
bar(Xray, Baz)
private
Foo
bar(Alpha, Baz)
String
public class Foo {
private String bar(Xray xray, Baz baz) { return "Xray"; }
private String bar(Zulu zulu, Baz baz) { return "Zulu"; }
public void bar(Alpha alpha, Baz baz) { // this one returns nothing
if(alpha.get() instanceof Xray) {
System.out.println(bar((Xray) alpha.get(), baz));
return;
} else if(alpha.get() instanceof Zulu) {
System.out.println(bar((Zulu)alpha.get(), baz));
return;
} else {
return;
}
}
}
当所有方法具有相同的返回类型时,用户 kswaughs解决了私有重载方法的问题。在其他地方,建议将该when()
方法与Method
对象一起使用......但是,现在我已经定义bar(Alpha, Baz)
使用与其他方法不同的返回类型,所有这些都再次分崩离析:
@RunWith(PowerMockRunner.class)
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 = PowerMockito.spy(foo);
Method m = Whitebox.getMethod(Foo.class, "bar", Xray.class, Baz.class);
PowerMockito.doReturn("ok").when(stub, m);
stub.bar(alpha, baz); // fails here - even though that then calls stub.bar(Xray, Baz);
// Testing if bar(Xray, Baz) was called by bar(Alpha, Baz)
PowerMockito.verifyPrivate(stub, times(5)).invoke("bar", any(Xray.class), any(Baz.class));
}
}
所有美丽的例外:
org.mockito.exceptions.base.MockitoException:
'bar' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. The method you are trying to stub is *overloaded*. Make sure you are calling the right overloaded version.
2. Somewhere in your test you are stubbing *final methods*. Sorry, Mockito does not verify/stub final methods.
3. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
at FooTest.testBar_callsBarWithXray(FooTest.java:31)
使用.withArguments(any(Xray.class), any(Baz.class))
似乎没有什么不同。
在现场,不幸的是,异常并没有说明如何通过我的设置来实现第 1 点。有任何想法吗?