我的测试对象中有这段代码:
public class Widget {
private Set<Thing> things;
public Set<Thing> getThings() { return things; }
public void setThings(Set<Thing> things) { this.things = things; }
public void performAction(PerformingVisitor performer) {
for (Thing thing: getThings())
{
thing.perform(performer);
}
}
}
我的JUnit / Mockito测试看起来像:
@RunWith(MockitoJUnitRunner.class)
public class WidgetTest {
@Mock private PerformingVisitor performer;
@Mock private Thing thing;
@InjectMocks private Widget widget;
@Before
public void setUp() throws Exception {
Set<Thing> things = new HashSet<Thing>();
things.add(thing);
widget.setThings(things);
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldPerformThing() {
Mockito.when(thing.perform(Mockito.any(PerformingVisitor.class))).thenReturn(true);
widget.performAction(performer);
Mockito.verify(thing).perform(Mockito.any(PerformingVisitor.class));
}
}
然而,这给了我错误:
Wanted but not invoked:
thing.perform(<any>);
-> at com.myclass.ThingTest.shouldPerformThing(WidgetTest.java:132)
我已验证代码是否进入for
循环并且应该调用实际的thing.perform(performer);
行,但我的模拟似乎没有录制通话。
答案 0 :(得分:1)
我认为在模拟注射之前你需要initMocks
。
您可以尝试为此更改setUp方法:
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
Set<Thing> things = new HashSet<Thing>();
things.add(thing);
widget.setThings(things);
}
希望它有效
答案 1 :(得分:1)
来自MockitoJUnitRunner
javadoc:
初始化用Mock注释的模拟,因此不需要明确使用MockitoAnnotations.initMocks(Object)。
所以,如果你删除
MockitoAnnotations.initMocks(this)
来自您的setUp
方法,即测试通行证。