我在我的主题这段代码在测试:列表中的一个元素惩戒方法
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);
一行,但我的模拟似乎没有录制电话。
Doh!是的,这是一个愚蠢的错误。谢谢。 – 2014-09-01 07:26:20
它的作品,但声明'MockitoAnnotations.initMocks(this);'是无用的。 – gontard 2014-09-01 07:30:19