I’ve written a stream that calls the foobarMethod, potentially triggering the mono of a SocketTimeoutException. I want this method to retry 2 times. Manually, this code works but in the junit test I can’t get it to retry. Is this because of an environment issue with unit tests or have I dont the tests wrong? Any help gratefully received. Thanks.
public void foobarServiceMethod() {
foobarClient.foobarMethod(foobarParameter)
.onErrorMap(ex -> {
log.error("Code has failed");
if (ex instanceof SocketTimeoutException) {
return new SocketTimeoutException("");
} else {
return ex;
}
})
.retryWhen(
Retry.fixedDelay(3, Duration.ofSeconds(1))
.filter(SocketTimeoutException.class::isInstance))
.subscribe(foobarResponse -> handleFoobarResoponse(foobarResponse));
@Test
void foobarRest(CapturedOutput capturedOutput) throws SocketTimeoutException, InterruptedException {
foobarParameter = "test";
when(foobarClient.foobarMethod(any()))
.thenReturn(Mono.error(new SocketTimeoutException("First timeout")))
.thenReturn(Mono.error(new SocketTimeoutException("First timeout")));
foobarMethod(foobarParameter);
assertEquals(2, capturedOutputSplit.contains("Code has failed");
}
For running tests on reactive you have to use reactor-test
dependency, instead of executing separately reactive code with subscribe
, you have to call it with StepVerifier.create(<your publisher>)
. more details can be found here
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
<version>3.7.1</version>
</dependency>
public Mono<Foo> foobarServiceMethod() {//return Mono/Flux dependig of result of foobarClient.foobarMethod
return foobarClient.foobarMethod(foobarParameter)
.onErrorMap(ex -> {
log.error("Code has failed");
if (ex instanceof SocketTimeoutException) {
return new SocketTimeoutException("");
} else {
return ex;
}
})
.retryWhen(
Retry.fixedDelay(3, Duration.ofSeconds(1))
.filter(SocketTimeoutException.class::isInstance));
@Test
void foobarRest(CapturedOutput capturedOutput) throws SocketTimeoutException, InterruptedException {
foobarParameter = "test";
when(foobarClient.foobarMethod(any()))
.thenReturn(Mono.error(new SocketTimeoutException("First timeout")))
.thenReturn(Mono.error(new SocketTimeoutException("First timeout")));
StepVerifier.create(foobarMethod(foobarParameter))
.expectErrorSatisfies(..)// error verify logic
//.expectNextMatches(...) OR check on success
.expectComplete()
.verify();
}