У меня есть этот код в моей теме:
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);
но мой макет, похоже, не записывает вызов.
Я думаю, вам нужно initMocks
перед макетной инъекцией.
Не могли бы вы попытаться изменить метод setUp для этого:
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
Set<Thing> things = new HashSet<Thing>();
things.add(thing);
widget.setThings(things);
}
Надеюсь, что это работает
Из MockitoJUnitRunner
javadoc:
Инициализирует mocks, аннотированный с помощью Mock, так что явное использование MockitoAnnotations.initMocks(Object) не требуется.
Итак, если вы удалите
MockitoAnnotations.initMocks(this)
от вашего метода setUp
, теста.
MockitoAnnotations.initMocks(this);
бесполезно.