Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing onErrorResume() Spring Webflux

I have a service layer using Spring Webflux and reactor and I am writing unit test for this. I was able to test the good response scenario but not sure how to test onErrorResume() using StepVerifier. Also please let me know if there is a better way of handling exceptions in my controller(e.g: using switchIfEmpty())

Here is my controller method

    public Mono<SomeType> getInfo(Integer id) {
            return webClient
                    .get()
                    .uri(uriBuilder -> uriBuilder.path())
                    .header("", "")
                    .header("", "")
                    .header("", "")
                    .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
                    .retrieve()
                    .bodyToMono(POJO.class)
                    .onErrorResume(ex -> {
                        if (ex instanceof WebFaultException)
                            return Mono.error(ex);
                        return Mono.error(new WebFaultException(ex.getMessage(), "Error on API Call", HttpStatus.INTERNAL_SERVER_ERROR));
                    });
        }
    }
like image 957
sai23 Avatar asked Nov 07 '25 01:11

sai23


1 Answers

You can mock the webclient and use Mockito.doThrow when webclientMock.get() is called.


YourWebClient webclientMock = mock(YourWebClient.class);


doThrow(RuntimeException.class)
      .when(webclientMock)
      .get();

// Call your method here

 Exception exception = assertThrows(RuntimeException.class, () -> {
        YourController.getInfo(someIntValue);
    });

// If you chose to raise WebFaultException, addittionaly assert that the return values ( message, status) are the one you expected

like image 108
exaucae Avatar answered Nov 09 '25 16:11

exaucae