I am trying to implement a test with a RetryConfig. Although I say which exception should be retried, nothing happens. The error is thrown and the test is finished. Fallback-method is also not trigered. Whats wrong with my test?
TestConfig.java
@TestConfiguration
public class TestRetryConfig {
@Autowired
private RetryRegistry retryRegistry;
@Bean("FeignRetry")
public Retry retryWithCustomConfig() {
RetryConfig customConfig = RetryConfig.custom()
.maxAttempts(3)
.waitDuration(Duration.ofSeconds(1))
.retryExceptions(FeignException.class)
.build();
return retryRegistry.retry("feignException", customConfig);
}
}
TestClass.java
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {MyAdapter.class, InMemoryRetryRegistry.class, ServerInternalErrorVerifier.class, TestRetryConfig.class})
class MyAdapterRetryTest {
@Autowired
private RetryRegistry registry;
@Autowired
private MyAdapter myAdapter;
@Autowired
private Retry retry; //i see here, that my retry has been injected correctly with defined bean-name
@MockBean
private MyClient myClient;
@Test
Request feignRequest =
Request.create(Request.HttpMethod.POST, "", Map.of(), "".getBytes(StandardCharsets.UTF_8), null, null);
FeignException.InternalServerError feignException =
new FeignException.InternalServerError("", feignRequest, "".getBytes(StandardCharsets.UTF_8), null);
when(myClient.sendPerson(any())).thenThrow(feignException); //here should retry be trigered
String result = myAdapter.sendPerson(myRequest);
assertThat(result).contains("was not send successfully");
}
}
My Prod-Method
@Retry(name = "throwingFeignException", fallbackMethod = "logCommunicationFailure")
public String sendPartner(MyRequest myRequest) {
MyResponse response = myClient.sendPerson(myRequest);
return "ok";
}
private String logCommunicationFailure(MyRequest myRequest, Exception exception) {
return "fail";
}
TL;DR:
The short answer is: you need to call
Retry.decorateFunction()with yourRetry retryobject and thesendPartner()method from the 'My Prod-Method' snippet you provided (there is an inconsistency, since you're referring tosendPerson()in your test -- I reckon you refer to the same method and it's just a typo.This will execute your
sendPartner()method decorated with@Retryand verifies it was retried 3 times as you configured.Long Answer: A Working Example
FeignRetryConfiguration Bean
FeignService Bean
The MyClient
Person is a POJO - skipping for brevity
The actual unit test
Certainly you need to extend this code to make it work as expected, but hopefully it will demonstrate how to make it happen.