How to write Component Test for the service class which uses returns Mono?

Viewed 364

I have a REST API-based application in Spring Boot which used Spring Webflux. As usual, the REST call flow looks like this:

RestController -> Service -> Another Microservice (REST Call)

The Service class uses WebClient to make the HTTP call to another service and returns a Mono, like:

private Mono<SubmissionResponse> submit(Submission mySubmission)  {

  Mono<Void> 201Response = webClient
        .post()
        .uri("/submit")
        .body(Mono.just(mySubmission), Submission.class)
        .retrieve()
        .onStatus(status -> status.equals(HttpStatus.NOT_FOUND), resp -> Mono.just(new SubmissionNotFoundException("No Submission found", HttpStatus.NOT_FOUND.name())))
        .bodyToMono(Void.class);

    return 201Response.map(r -> myResponseGenerator.generateResponse(mySubmission));
}

I have a wire mock server started during the Component Test. The test case code looks like:

Mono<SubmissionResponse> submissionResponse = submissionService.submit(mySubmission);
SubmissionResponse response = submissionResponse.block();

In the above test case code, the response object is always null.

1 Answers

Mono<Void> can never emit a value, only a completion signal. Therefore, the Mono<Void> 201Response will not emit data, so map will not be triggered.

Try this:

.bodyToMono(Void.class)
.thenReturn(myResponseGenerator.generateResponse(mySubmission));

Here, the thenReturn operator will emit the provided value.

Related