获取模拟调用的次数

时间:2014-08-28 07:38:02

标签: java junit mockito

假设我想测试这样的代码:

class ClassToTest
  // UsedClass1 contains a method UsedClass2 thisMethod() {}
  UsedClass1 foo;
  void aMethod()
  {
    int max = new Random().nextInt(100);
    for(i = 0; i < max; i++)
    {
      foo.thisMethod().thatMethod();
    }
  }
}

如果我有这样的测试:

ClassToTest test;
UsedClass1 uc1;
UsedClass2 uc2;
@Test
public void thingToTest() {
  test = new ClassToTest();
  uc1 = mock(UsedClass1.class);
  uc2 = mock(UsedClass2.class);
  when(uc1.thisMethod()).thenReturn(uc2);
  when(uc2.thatMethod()).thenReturn(true);

  test.aMethod();

  // I would like to do this
  verifyEquals(callsTo(uc1.thisMethod()), callsTo(uc2.thatMethod()));
}

如何获得uc1.thisMethod()uc2.thatMethod()的来电次数,以便我可以检查它们的呼叫次数是否相同?

4 个答案:

答案 0 :(得分:15)

You can do something like this:

YourService serviceMock = Mockito.mock(YourService.class);

// code using YourService

// details of all invocations including methods and arguments
Collection<Invocation> invocations = Mockito.mockingDetails(serviceMock).getInvocations();
// just a number of calls of any mock's methods
int numberOfCalls = invocations.size();

If you want only the invocations of certain method/param combination you, you can do so with

int specificMethodCall = Mockito.mockingDetails(serviceMock.myMethod(myParam)).getInvocations()

答案 1 :(得分:7)

你可以存根你的方法,并增加一个计数器,如下所示:

final AtomicInteger countCall1 = new AtomicInteger();

Mockito.doAnswer(new Answer<UsedClass2>() {
    @Override
    public UsedClass2 answer(InvocationOnMock invocation) throws Throwable {
        countCall1.incrementAndGet();
        return uc2;
    }
}).when(uc1).thisMethod();

答案 2 :(得分:3)

如果您知道调用方法的次数,可以使用Mockito的times()方法

//for example if had to be called 3 times
verify(uc1, times(3)).thisMethod();
verify(uc2, times(3)).thatMethod();

但是,我现在看到你把这个方法调用了一次,所以这可能不是最好的答案,除非你把随机数生成器固定下来以便总是返回一个期望值。

答案 3 :(得分:2)

您可以使用自定义VerificationMode来计算调用次数:

public class InvocationCounter {

    public static <T> T countInvocations(T mock, AtomicInteger count) {
        return Mockito.verify(mock, new Counter(count));
    }

    private InvocationCounter(){}

    private static class Counter implements VerificationInOrderMode, VerificationMode {
        private final AtomicInteger count;

        private Counter(AtomicInteger count) {
            this.count = count;
        }

        public void verify(VerificationData data) {
            count.set(data.getAllInvocations().size());
        }

        public void verifyInOrder(VerificationDataInOrder data) {
            count.set(data.getAllInvocations().size());
        }

        @Override
        public VerificationMode description(String description) {
            return VerificationModeFactory.description(this, description);
        }

    }

}

然后像这样使用它(也适用于void返回类型):

@Mock
private Function<String, Integer> callable;

AtomicInteger count= new AtomicInteger(); //here is the actual invocation count stored

countInvocations(callable,count).apply( anyString());

assertThat(count.get(),is(2));