假设我想测试这样的代码:
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()的调用次数,以便我可以检查它们被调用的次数相同?
解决方法
您可以使用自定义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));