【发布时间】:2018-01-19 14:01:01
【问题描述】:
我面临的问题是我需要跟踪某些方法的调用,但只能使用指定的参数参数。请参阅下面的问题
@Test
public void simpleTest() {
ArgumentCaptor<Pear> captor = ArgumentCaptor.forClass(Pear.class);
Action action = mock(Action.class);
action.perform(new Pear());
action.perform(new Apple());
verify(action, times(1)).perform(captor.capture());
}
static class Action {
public void perform(IFruit fruit) {}
}
static class Pear implements IFruit {}
static class Apple implements IFruit {}
interface IFruit {}
但是得到:
org.mockito.exceptions.verification.TooManyActualInvocations:
action.perform(<Capturing argument>);
Wanted 1 time:
But was 2 times. Undesired invocation:
..
我做错了什么? Mockito v 1.10
老实说,这只是一个例子,我的代码更复杂,我不知道,Apple.class 会调用多少次 perform。对我来说没关系。我只需要验证 perform(Pear.class) 的调用
统一更新: 我需要验证使用 Pear.class 的方法是否被调用过一次。让我们假设 Action 是 Transaction,而 perform 是 save(DomainObject)。所以我需要确保 save(MyDomainObject) 被调用一次,但无论之前保存了多少个对象。这个动作对于测试来说是原子的,我不能在这些操作之间重置模拟
【问题讨论】:
-
你调用了两次,然后试图验证你只调用了一次?
-
@Berger 在他的情况下,测试通过应该是次(2)次
-
但我只想验证参数类型为 Pear.class 的方法的调用。任何想法怎么做?
-
尝试
verify(action, times(1)). perform(argumentThat(yourImplementation) )检查参数