我遇到了一个问题,需要跟踪某个方法的调用,但只针对特定的参数进行跟踪。请参见以下问题:
@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版本1.10
说实话,这只是一个例子,我的代码更加复杂,而且我不知道perform方法会被调用多少次,使用Apple类。这对我来说不重要。我只需要验证针对Pear类的perform方法是否被调用。
更新: 我需要验证使用Pear类的方法是否被调用一次。比方说,Action是Transaction,perform是save(DomainObject)。我需要确保save(MyDomainObject)被调用了一次,但不管之前保存了多少个对象。这个操作对于测试来说是原子操作,我不能在这些操作之间重置模拟对象。
verify(action, times(1)). perform(argumentThat(yourImplementation))
来检查参数。 - Alexander.Furer