Mockito:验证多次调用异常的方法

6xfqseft  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(292)

有没有人可以提供以下建议?我有一个方法,如果在数据库中找不到任何东西,就会抛出异常,这是业务需求。而且,方法通过Spring xml AOP实现了重试。因此,该方法应该运行几次,然后失败并出现异常。有没有办法使用Mockito来计算该方法被调用的次数?
这一个不起作用:

verify(mock, times(5)).method();

因为最后一个方法调用抛出了异常,而这个异常无法验证自身。我尝试了@Test(expected = ...),但它只是捕获了最后一个异常,并跳过了验证。

kh212irz

kh212irz1#

请考虑:

package de.test;
    public class MyService {
      int invocations = 0;
      public void doSomething(int x){
        invocations++;
        if (invocations==5){
          throw new RuntimeException("exception");
        }
        return;
      };
    }

    package de.test;

    public class MyProcessor {
      private MyService myService;

      public MyProcessor(MyService myService) {
        this.myService = myService;
      }

      public void process(int n) {
        myService.doSomething(n);
        System.out.println("Processed: " + n);
      }
    }

此测试代码:

package de.test;

  import de.bodo.MyProcessor;
  import de.bodo.MyService;
  import org.junit.jupiter.api.Test;
  import org.mockito.Mockito;

  public class ProcessorTest {

    @Test
    public void processTest() {
      MyService myService = Mockito.spy(new MyService());
      MyProcessor myProcessor = new MyProcessor(myService);

      myProcessor.process(0);
      myProcessor.process(1);
      myProcessor.process(2);
      myProcessor.process(2);
      RuntimeException thrown = assertThrows( RuntimeException.class,
         ()-> myProcessor.process(2),
         " expected exception" );
      myProcessor.process(2);

      Mockito.verify(myService, Mockito.atMostOnce()).doSomething(0);
      Mockito.verify(myService, Mockito.atMostOnce()).doSomething(1);
      Mockito.verify(myService, Mockito.atMost(4)).doSomething(2);
      Mockito.verify(myService, Mockito.atLeastOnce()).doSomething(1);
      Mockito.verify(myService, Mockito.atLeast(2)).doSomething(2);
      Mockito.verify(myService, Mockito.times(4)).doSomething(2);
      Mockito.verify(myService, Mockito.never()).doSomething(3);    
    }
  }

因此,您不仅可以检查方法被调用的频率,甚至还可以计算使用一个特定参数(本例中为整数)调用方法的频率。
您需要将Mockito添加到pom.xml中:

!-- https://mvnrepository.com/artifact/org.mockito/mockito-junit-jupiter -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>

来源:https://www.logicbig.com/tutorials/unit-testing/mockito/verifying-varing-number-of-invocations.html

相关问题