【问题标题】:Unit test - Problems testing @Retryable and @Recover单元测试 - 测试 @Retryable 和 @Recover 的问题
【发布时间】:2019-09-18 08:37:57
【问题描述】:

我有一个使用 @Retryable 注释的组件和另一个使用该组件的服务。所以我试图测试使用@Retryable注解的组件实际上是在重试。

我现在已经尝试了网络上的所有解决方案,但没有一个对我有用。我正在尝试为此创建一个单元测试,而不是集成测试。到目前为止,我已经设法解决了应该抛出的异常,而 @Retryable 甚至没有重试,该方法只是抛出了异常,仅此而已。

这是使用 Retryable 注解的组件:

@Component
public class OurComponent {

    @Retryable(maxAttempts = 10,
            backoff = @Backoff(delay = 2000),
            value = {someException.class}
    )
    public void someMethod(SomeObject someObject) throws someException {
        Object createObject = anotherMethod(someObject); //this method throws someException
        ...
    }
}

以及使用这个ourComponent的服务:

@Service
public class someService {

    private final OurComponent ourComponent;

    public SomeService(OurComponent ourComponent) {
         this.ourComponent = ourComponent;
    }

    ...


    public void methodUsingComponent() {
         SomeObject someObject = new SomeObject(args);
         ourComponent.someMethod(someObject);
    }
}

现在我尝试@InjectMocks 和@MockBean 这个服务和组件,但它仍然没有工作。甚至可以在不进行集成测试的情况下测试@Retryable 注解吗?

【问题讨论】:

    标签: spring spring-boot unit-testing junit mockito


    【解决方案1】:

    如果你使用一个根本不使用 spring 的单元测试,你将无法轻松测试它。

    这是因为这样的注解可以被spring识别,并且相应的bean被一个运行时生成的代理包裹着,该代理实现了“重试”逻辑。

    现在,如果你没有触发这一切机制的spring,这个@Retryable注解基本没用,mockito什么都不知道,Junit也是。

    您可以尝试手动创建这样的代理(检查 spring-retry 调用的逻辑),但它看起来有点矫枉过正。坦率地说,它没有给你任何东西。单元测试应该检查您的代码的功能,而不是在其他地方实现并经过测试的 spring 重试背后的逻辑。

    【讨论】:

      猜你喜欢
      • 2021-06-22
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多