试图找出最好的方法来做一些看起来很简单的事情:测试一个特定的方法正在被测试类的协作者上调用。我在 JDK 6 中使用 Mockito (1.9.5) 和 PowerMock (1.5.1)。
一般的做法是通过 Mockito 设置部分模拟spy
,通过 PowerMock 方法设置内部状态WhiteBox
,然后调用我正在测试的方法:creatFoo()
.
尽可能简化代码,同时仍然了解我的意思。这是正在测试的类:
public class FooGate {
BlackBox.Factory factory;
BlackBox.Bar bar;
public void createFoo(Foo foo) {
bar = factory.produce(BlackBox.Bar.class);
bar.create(bbFoo);
}
...
}
这是不起作用的测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest(FooGate.class)
public class FooGateTest {
@Test
public void test() {
FooGate testGate = Mockito.spy(new FooGate());
BlackBox.Factory mockfactory = mock(BlackBox.Factory.class);
BlackBox.Bar mockBar = mock(BlackBox.Bar.class);
WhiteBox.setInternalState(testGate, BlackBox.Factory, mockFactory);
WhiteBox.setInternalState(testGate, BlackBox.Bar, mockBar);
Foo foo = new Foo();
foo.setSetting("x");
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
... do stuff ...
}
}).when(mockBar).create(any(Foo.class));
// NPE here: seems like bar is null in testGate.
testGate.createFoo(foo);
assertStuff(...);
}
}
如果我删除 WhiteBox.set... 因为Factory
我在factory.produce()
. 所以,这似乎奏效了。
但doAnswer()
显然不是。或者是其他东西。
绝对对完成相同事情的其他方法持开放态度,但想知道我在这里缺少什么。
注意:看起来这不是导入的问题,所以我省略了它们,但如果你认为它们有用,我可以包括它们。