Unable to get resilience4j retry annotation to execute in Springboot unit test

Viewed 540

I'm trying to write a unit test to validate my resilience4j app with the @retry annotation, but it's not retrying at all. The code works when I run it, just can't get it unit tested.. Any ideas?

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {ClassImTesting.class})
public class MyCoolTest {

    @Autowired
    private MyClass thing;


    @Test
    public void myTest() throws TransformationException {
        thing.transform(null);
    }

ClassImTesting

  @Override
  @Retry(name = "transformer", fallbackMethod = "handleFailure")
  public void transform(Thing record)
      throws TransformationException {
    return this.transform(record.value());
  }

public void handleFailure(Thing record, Throwable t) {
   // stuff
}
1 Answers

What needs to be done in the unit test is auto wire the RetryRegistry, then use it to grab the Retry object that is configured for your service method, then execute it using the retry. Also make sure to include the Retry Auto config on the test class. Like this:

@SpringBootTest(classes = {RetryAutoConfiguration.class, ClassImTesting.class})
public class MyCoolTest {

  @Autowired
  private MyClass thing;

  @Autowired
  private RetryRegistry registry;

 @Test
 public void myTest() throws TransformationException {
     final Retry transformerRetry = registry.retry("transformer");
     transformerRetry.executeSupplier(() -> thing.transform(null));
  }
}

https://github.com/resilience4j/resilience4j/blob/master/resilience4j-retry/src/test/java/io/github/resilience4j/retry/internal/SupplierRetryTest.java#L90

Related