模拟列表元素中的方法



我的受试者中有以下代码:

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);行,但我的mock似乎没有记录调用。

我认为在模拟注入之前需要initMocks

你能试着改变你的设置方法吗:

   @Before
   public void setUp() throws Exception {
      MockitoAnnotations.initMocks(this);
      Set<Thing> things = new HashSet<Thing>();
      things.add(thing);
      widget.setThings(things); 
   }

希望它能在上运行

来自MockitoJUnitRunner javadoc:

初始化用Mock注释的Mock,这样就不需要显式使用MockitoAnnotations.initMocks(Object)。

所以,如果你删除

 MockitoAnnotations.initMocks(this)

从您的setUp方法,测试通过。

相关内容

  • 没有找到相关文章