java – 获取模拟的调用次数

前端之家收集整理的这篇文章主要介绍了java – 获取模拟的调用次数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我想测试这样的代码
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));
原文链接:https://www.f2er.com/java/128390.html

猜你在找的Java相关文章