Java 模拟列表元素中的方法
我的测试对象中有以下代码:Java 模拟列表元素中的方法,java,mockito,Java,Mockito,我的测试对象中有以下代码: 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(Performing
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);
}
}
}
公共类小部件{
私设物品;
public Set getThings(){return things;}
public void setThings(Set things){this.things=things;}
公开无效表演(表演观众-表演者){
for(Thing:getThings())
{
表演(表演者);
}
}
}
我的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));
}
}
@RunWith(MockitoJUnitRunner.class)
公共类Widgetest{
@模拟私人表演;
@模仿私事;
@注入mock私有小部件;
@以前
public void setUp()引发异常{
Set things=newhashset();
事物。添加(事物);
widget.setThings(things);
initMocks(this);
}
@试验
公物{
Mockito.when(thing.perform(Mockito.any(PerformingVisitor.class)),然后返回(true);
widget.performation(表演者);
Mockito.verify(thing).perform(Mockito.any(PerformingVisitor.class));
}
}
但是,这给了我一个错误:
Wanted but not invoked:
thing.perform(<any>);
-> at com.myclass.ThingTest.shouldPerformThing(WidgetTest.java:132)
需要但未调用:
事物。执行();
->在com.myclass.ThingTest.shouldperformating(widgetest.java:132)
我已经验证代码是否进入了
for
循环,并且应该调用实际的东西代码>行,但我的mock似乎没有录制呼叫。我认为在模拟注入之前需要initmock
您是否可以尝试为此更改设置方法:
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
Set<Thing> things = new HashSet<Thing>();
things.add(thing);
widget.setThings(things);
}
@之前
public void setUp()引发异常{
initMocks(this);
Set things=newhashset();
事物。添加(事物);
widget.setThings(things);
}
希望它能工作来自MockitoJUnitRunner
:
初始化用Mock注释的Mock,这样就不需要显式使用MockitoAnnotations.initMocks(Object)
所以,如果你删除
MockitoAnnotations.initMocks(this)
通过设置
方法,测试通过 它可以工作,但是语句MockitoAnnotations.initMocks(this)代码>是无用的。