如何模拟jcabi注释参数

时间:2015-07-27 10:05:04

标签: java unit-testing junit mocking jcabi

我有一些代码如下。

@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 变量的值来自单独的常量 class,是int primitive。这两个变量都定义为 public static final

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

我已经尝试了两种方法:两种方法都不起作用

  
      
  1. 将PowerMock与Whitebox.setInternalState()一起使用。
  2.   
  3. 也使用反射。
  4.   

修改
如@ yegor256所述,那是不可能的,我想知道,为什么不可能?当这些注释被加载?

1 个答案:

答案 0 :(得分:1)

无法在运行时更改它们。你要做的是为了使你的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();
  }
}

这是你能做的最好的事情。不幸的是