简体   繁体   中英

How to test Controller that returns Mono<ResponseEntity<Void>>?

I'm pretty new to webflux and I am struggling to understand how to test this Controller function.

    public Mono<ResponseEntity<Void>> functionName(final Request request) {
    RequestDto Dto = RequestMapper.
            INSTANCE.toDto(request);
    service.functionName(Dto);
    return Mono.just(new ResponseEntity<Void>(HttpStatus.OK));
}

You could use WebTestClient that provides fluent API for verifying responses. Here is a short example

@WebFluxTest
class ControllerTest {

    @Autowired
    private WebTestClient client;

    @BeforeEach
    void setUp(ApplicationContext context) {
        client = WebTestClient.bindToApplicationContext(context).build();
    }

    @Test
    void test() {
        client.get()
                .uri("/test")
                .exchange()
                .expectStatus().isOk()
                .expectBody().isEmpty();
    }
}

In addition, pay attention to endpoint implementation. In reactive you need to build the flow and Webflux will subscribe to it for every request. In case, service.functionName is blocking (non-reactive), consider running it on a separate Scheduler using .subscribeOn(Schedulers.boundedElastic()) . For details, check How Do I Wrap a Synchronous, Blocking Call? .

If the Callable resolves to null , the resulting Mono completes empty and we could return 404 applying switchIfEmpty operator.

@GetMapping(path = "/test")
public Mono<ResponseEntity<Void>> functionName(Request request) {
    return Mono.fromCallable(() -> {
                RequestDto Dto = RequestMapper.INSTANCE.toDto(request);
                return service.functionName(Dto);
            }).subscribeOn(Schedulers.boundedElastic())
            .map(res -> new ResponseEntity<>(HttpStatus.OK))
            .switchIfEmpty(Mono.just(new ResponseEntity<>(HttpStatus.NOT_FOUND)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM