我有一些类似下面的代码。

@RetryOnFailure(attempts = Constant.RETRY_ATTEMPTS, delay = Constant.RETRY_DELAY, unit = TimeUnit.SECONDS)
public void method() {
    // some processing
    //throw exception if HTTP operation is not successful. (use of retry)
}


RETRY_ATTEMPTS和RETRY_DELAY变量的值来自单独的Constant类,它们是int原语。这两个变量都定义为public static final。

在编写单元测试用例时,如何覆盖这些值。实际值会增加单元测试用例的运行时间。

我已经尝试了两种方法:两种方法均无效


  
  将PowerMock与Whitebox.setInternalState()一起使用。
  以及使用反射。
  




编辑:
如@ yegor256所提到的,我想知道为什么不可能吗?这些注释何时加载?

最佳答案

无法在运行时更改它们。为了使您的method()可测试,您应该做的是创建一个单独的“装饰器”类:

interface Foo {
  void method();
}
class FooWithRetry implements Foo {
  private final Foo origin;
  @Override
  @RetryOnFailure(attempts = Constant.RETRY_ATTEMPTS)
  public void method() {
    this.origin.method();
  }
}


然后,出于测试目的,请使用Foo的另一种实现:

class FooWithUnlimitedRetry implements Foo {
  private final Foo origin;
  @Override
  @RetryOnFailure(attempts = 10000)
  public void method() {
    this.origin.method();
  }
}


那是你所能做的最好的。不幸。

09-10 21:17
查看更多