0

I have an simple class to test @Retryable annotation:

@Component
public class SimpleRetryComponent {

  private final AtomicLong counter = new AtomicLong(0L);

  @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 100, multiplier = 2,maxDelay = 500))
  public long retryableMethod(boolean shouldThrowException) {
      var count = counter.incrementAndGet();
      if (shouldThrowException) {
          throw new RuntimeException("Exception requested.");
      }
      return count;
  }
}

And I have the simple test for it:

@ExtendWith(SpringExtension.class)
@Import(SimpleRetryComponent.class)
@EnableRetry
class SimpleRetryComponentTest {

  @Test
  void retryableMethod_shouldRetry_whenExceptionThrown() {
    var simpleRetryComponent = new SimpleRetryComponent();

    Awaitility.await()
            .atMost(Duration.of(10, SECONDS))
            .untilAsserted(() -> simpleRetryComponent.retryableMethod(true));
  }
}

But when I run the test, the counter is incremented only once, then I get RuntimeException and application stops (so it looks like @Retryable takes no effect. As you see, I use @ExtendWith(SpringExtension.class) and @EnableRetry in my test. What am I missing?

To add @Retryable, I added to pom.xml:

<dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
  <version>2.0.0</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
</dependency>
PolGraphic
  • 3,233
  • 11
  • 51
  • 108
  • 1
    Autowire the component, don't create a new instance. I also doubt `@EnableRetry` on a test will do any good, as it should be on a configuration class which you should load in your test. – M. Deinum Jun 26 '23 at 08:53
  • Autowire was the point. Can you make your comment as an answer? About the `@EnableRetry` on test itself, I've seen in many answers to different related questions, e.g. (and it works fine when I corrected the Autowire part): https://stackoverflow.com/questions/39478665/springs-retryable-not-working-when-running-junit-test – PolGraphic Jun 26 '23 at 08:58

0 Answers0