我在我的主題這段代碼在測試:列表中的一個元素懲戒方法
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