java - 获取对模拟的调用次数

标签 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() 的调用次数,这样我就可以检查它们都被调用了相同的次数?

最佳答案

你可以这样做:

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();

如果您只想调用某些方法/参数组合,您可以这样做

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

关于java - 获取对模拟的调用次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25543250/

相关文章:

java - 如何配置 ActiveMQ 以将 'anonymous' 用户和角色分配给未经身份验证的用户

java - 无法初始化类 liquibase.sqlgenerator.core.LockDatabaseChangeLogGenerator

java - 使用 JUnit 和 AssertJ 测试数组是否包含元素

java - 如何对返回 Java 字符串的方法进行单元测试?

java - Matchers.any() 用于 Mockito 中的空值

java - Bean 属性不可读或具有无效的 getter 方法

java - 有人可以简单解释一下这个Java行吗?

java - 将 recyclerView 焦点/滚动到最后一个项目

java - 在 JUnit 测试中,如何在不考虑它们的类型的情况下断言两个数字相等?

android - 模拟 SharedPreferences.Editor.putString()