gpt4 book ai didi

java - 模拟列表元素中的方法

转载 作者:行者123 更新时间:2023-11-30 03:46:20 26 4
gpt4 key购买 nike

我的测试主题中有此代码:

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); 行,但我的模拟似乎没有正在录音。

最佳答案

我认为在模拟注入(inject)之前你需要initMocks

您可以尝试更改您的设置方法吗:

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

希望有效果

关于java - 模拟列表元素中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25599875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com