1

I have some code like below.

@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)
}

The value of RETRY_ATTEMPTS and RETRY_DELAY variable come from a separate Constant class, which are int primitive. Both the variable are defined as public static final.

How can I override these values while writing the unit testcases. The actual values increases running time of unit testcases.

I have already tried two approach: Both did not work

  1. Using PowerMock with Whitebox.setInternalState().
  2. Using Reflection as well.

Edit:
As mentioned by @yegor256, that it is not possible, I would like to know, why it is not possible? When these annotations get loaded?

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73

1 Answers1

1

There is no way to change them in runtime. What you should do, in order to make your method() testable is to create a separate "decorator" class:

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

Then, for test purposes, use another implementation of Foo:

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

That's the best you can do. Unfortunately.

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • At the moment instead of annotations, I implemented my own class for doing the retries. I will try this approach for sure. – YoungHobbit Sep 26 '15 at 23:32
  • I have a further question, why it is not possible to overwrite these annotations? – YoungHobbit Sep 26 '15 at 23:51
  • Yes. That I understood previously. I meant what is so different about annotations that they can't be overridden, even through mocking frameworks and java reflections. – YoungHobbit Sep 28 '15 at 02:37
  • 1
    You can, actually, see http://stackoverflow.com/questions/14268981/modify-a-class-definitions-annotation-string-parameter-at-runtime/14276270 – yegor256 Sep 29 '15 at 15:49