【问题标题】:Asyn retry Junit is not running for 3 times as defaultAsyn retry Junit默认没有运行3次
【发布时间】:2021-07-20 18:09:14
【问题描述】:

我正在为可重试的失败场景进行 junit 测试。在我们升级到新版本的 mockito 和 spring boot 版本之前,它一直运行良好。我们已经更新到 spring boot 2.4.x 并开始看到这个问题。

Service.java

public class RetryTest 
{
    @Autowired
    private RetryTemplate retryTemplate;

    @Async
     private void retryTest(String in) {
          retryTemplate.execute( invoke -> {
                 callMethod(in);
                 return null;
          }, recoveryCallBack);
     }

     public void callMethod(String in) {
          //some service call on failruew need to retry this.
      someService.test(in);
    }
     
}

单元测试:

@RunWith(SpringJUint4Runner.class)
Public class Test {

    @InjectMocks
    private RetryTesr retryTest;

    @Mock
     private RetryTemplate retryTemplate;
    
    @Test(expected = ServiceException.class)
    public void testFailure() {
         when(someService.test(anyString())).ThenRetrun(new RuntimeException.class). ThenRetrun(new RuntimeException.class). ThenRetrun(new RuntimeException.class);
    
    retryTest.retryTest(in);
    
    }

}

当我在上面运行时,即使 retryTemplate 的默认值为 3 次,它也只执行一次。预期应该是它应该执行 3 次,然后它应该抛出一个服务异常,就像我们在 recoveryCallBack 中抛出的那样。

谁能推荐一下。

【问题讨论】:

  • 显示完整的测试类文件
  • @Deadpool 更新了完整的测试课程。谢谢

标签: spring-boot asynchronous junit retry-logic


【解决方案1】:

要测试任何 Spring 功能,您必须使用 @SpringBootTest 注释编写集成测试用例

@RunWith(SpringJUint4Runner.class)
@SpringBootTest
Public class Test {

@Autowired
private RetryTesr retryTest;

@MockBean
private RetryTemplate retryTemplate;

@Test(expected = ServiceException.class)
public void testFailure() {
     when(someService.test(anyString())).ThenRetrun(new RuntimeException.class). ThenRetrun(new RuntimeException.class). ThenRetrun(new RuntimeException.class);

retryTest.retryTest(in);

   }

}

【讨论】:

    【解决方案2】:

    它很奇怪。升级 spring boot 的版本后 ..Mockito.any() 不起作用,所以我必须使用确切的值来匹配 mock。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 2019-04-25
      相关资源
      最近更新 更多