java - 使用 Mockito 验证递归方法调用的最佳实践

标签 java unit-testing mocking mockito

考虑这个示例类:

public class Processor {
  private final Dependency dependency;

  public Processor(Dependency dependency) {
    this.dependency = dependency;
  }

  public void processUsers(List<Integer> userIds, int attempt) {
    if (attempt == 0) {
      //log initial processing
    } else if (attempt > 0 && attempt < 5) {
      //log retry processing
    } else {
      //log processing limit exceeded
      return;
    }
    List<Integer> failedIds = new ArrayList<Integer>();
    for (Integer userId : userIds) {
      try {
        processUser(userId);
      } catch (Exception ex) {
        //logging
        failedIds.add(userId);
      }
    }
    if (failedIds.isEmpty()) {
      //log ok
    } else {
      processUsers(failedIds, attempt + 1);
    }
  }

  public void processUser(Integer userId) throws Exception{
    //dependency can throw exception
    dependency.call();
  }
}

我想验证方法 processUsers 在抛出异常时调用自身。 这是我的暴躁测试:

public class ProcessorTest {
  @Test
  public void processShouldCallItselfWithFailedSublistWhenProcessingFails(){
    Dependency dependency = mock(Dependency.class);
    when(dependency.call()).thenThrow(Exception.class);
    Processor processor = new Processor(dependency);
    processor.processUsers(Arrays.asList(new Integer[]{1,2,3}), 0);
    //need to verify processor will call #processUsers recursively
    //because the dependency thrown Exception, how?
  }
}

验证该方法在特定情况下递归调用自身的最佳做法是什么?

我正在使用 TestNG + Mockito 和这种称为 JAVA 的冗长语言

最佳答案

您可以验证 dependency.call() 被调用的次数。这会告诉您重试有效 - 仅通过调用次数:

@Test
public void processShouldCallItselfWithFailedSublistWhenProcessingFails() {
    Dependency dependency = mock(Dependency.class);
    when(dependency.call()).thenReturn(1, 2).thenThrow(Exception.class).
        thenReturn(4);
    Processor processor = new Processor(dependency);
    processor.processUsers(Arrays.asList(new Integer[]{1, 2, 3}), 0);
    verify(dependency, times(4)).call();
}

这会告诉您重试最终因异常太多而失败:

@Test
public void processShouldFailAfterTooManyRetries() {
    Dependency dependency = mock(Dependency.class);
    when(dependency.call()).thenThrow(Exception.class);
    Processor processor = new Processor(dependency);
    final List<Integer> userIds = Arrays.asList(new Integer[]{1, 2, 3});
    final int expectedRetries = 5;
    processor.processUsers(userIds, 0);
    verify(dependency, times(expectedRetries * userIds.size())).call();
}

如果对依赖项的调用实际上使用了 userId,那么您实际上可以检查是否所有预期的对 dependency.call(int userId) 的调用都发生了。这会告诉你,如果有足够的重试,所有这些都通过了:

@Test
public void processShouldCallItselfWithFailedSublistWhenProcessingFails() {
    Dependency dependency = mock(Dependency.class);
    when(dependency.call(anyInt())).
        thenReturn(1, 2).thenThrow(Exception.class).thenReturn(4);
    Processor processor = new Processor(dependency);
    processor.processUsers(Arrays.asList(new Integer[]{1, 2, 3}), 0);
    verify(dependency).call(1);
    verify(dependency).call(2);
    verify(dependency, times(2)).call(3);
}

@Test
public void processShouldFailAfterTooManyRetries() {
    Dependency dependency = mock(Dependency.class);
    when(dependency.call(anyInt())).thenThrow(Exception.class);
    Processor processor = new Processor(dependency);
    final List<Integer> userIds = Arrays.asList(new Integer[]{1, 2, 3});
    final int expectedRetries = 5;
    processor.processUsers(userIds, 0);
    for (Integer userId : userIds) {
        verify(dependency, times(expectedRetries)).call(userId);
    }
}

关于java - 使用 Mockito 验证递归方法调用的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15835266/

相关文章:

java - 无法在 Groovy gradle 项目中找到或加载主类

c# - 如何使用提示对 Microsoft 机器人对话框进行单元测试

javascript - Jest - 监视嵌套的 promise (axios)

java - 如何模拟在测试方法中创建的对象?

python - 如何在测试的不同 python 源中模拟导入?

java - 如何从接收到的数据中正确提取信息?

Java - 程序在 Eclipse 中完美运行,但在导出到可运行 jar 时似乎没有执行其预期任务

java - 用jsoup解析表数据

javascript - Jest --runTestsByPath 两个或多个不同的路径

java - 如何使用 Mockito 测试不模拟对象的异步方法?