Spring Webflux,测试`ServerResponse` [英] Spring webflux, testing `ServerResponse`
问题描述
如何测试接收ServerRequest
并返回Mono<ServerResponse>
的 handler 方法?
How can I test a handler method that receive ServerRequest
and return Mono<ServerResponse>
?
我可以通过org.springframework.mock.web.reactive.function.server.MockServerRequest.builder()
创建一个ServerRequest
.并在ServerResponse.statusCode()
上断言.但是,我想测试此ServerResponse
的正文,但无法提取它.
I can create a ServerRequest
via org.springframework.mock.web.reactive.function.server.MockServerRequest.builder()
. And assert on the ServerResponse.statusCode()
. However I would like to test the body of this ServerResponse
but there is no way to extract it.
ServerResponse response = target.search(MockServerRequest.builder()
.method(HttpMethod.GET)
.build()
).block();
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
//assertThat(response.body()).isNotNull();
我不想用WebTestClient
做更广泛的测试,我想用单元测试来测试所有可能的响应情况.
I don't want to do a broader test with the WebTestClient
, I would like to test all possible cases of response with unit tests.
谢谢
推荐答案
因此,看来最好的解决方案是使用WebTestClient
.但是,可以在没有运行服务器的情况下使用此服务器.
So, it seems that the best solution is to use the WebTestClient
. However this one can be used without a running server;
spring-test
模块包含一个WebTestClient
,可用于测试具有或不具有运行服务器的WebFlux服务器端点 .
The
spring-test
module includes aWebTestClient
that can be used to test WebFlux server endpoints with or without a running server.
诀窍是使用bindTo..()
构建器方法.就我而言,bindToRouterFunction(new MyRouter(new MyHandler()))
效果很好
The trick is to use the bindTo..()
builder method. In my case bindToRouterFunction(new MyRouter(new MyHandler()))
works well
这篇关于Spring Webflux,测试`ServerResponse`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!