如何解决如何使用Functional API在WebFlux中测试没有RouterFunction的HandlerFunction?
我正在使用Kotlin中的Functional API用Spring WebFlux编写一个简单的HTTP服务器。
正如the documentation所说,HandlerFuction
通过在调用时返回ServerRequest
处理传入的Mono<ServerResponse>
。
假设,我们有以下函数,根据是否显示 name 路径变量,使用 OK 或 BAD_REQUEST 响应: / p>
val helloHandler = HandlerFunction { req ->
try {
val name = req.pathVariable("name")
ok().bodyValue("Hello $name!")
} catch (_: IllegalArgumentException) {
badRequest().build()
}
}
The Testing section of Spring Reference Guide意味着应该使用RouterFunction
将其与WebTestClient
结合使用进行测试。这样的测试看起来像这样:
val helloHandlerRouter = RouterFunctions.route()
.GET("/hello/{name}",helloHandler)
.build()
val client = WebTestClient
.bindToRouterFunction(helloHandlerRouter)
.build()
client.get().uri("/hello/Panda").exchange()
.expectStatus().isOk
.expectBody<String>().isEqualTo("Hello Panda!")
尽管此测试似乎令人满意,但它很大程度上取决于基础的路由机制。例如,在缺少 name 路径变量时,它将忽略实际的处理程序逻辑,而返回 NOT_FOUND 而不是 BAD_REQUEST 。路由器通过根本不将请求转发给处理程序ergo进行拦截,以下测试正在测试路由器而不是处理程序:
client.get().uri("/hello").exchange()
.expectStatus().isBadRequest // FAILS: NOT_FOUND != BAD_REQUEST
.expectBody().isEmpty
如何在没有路由器的情况下测试HandlerFunction
?
我想以某种方式单独测试HandlerFunction
:
val request = MockServerRequest.builder()
.pathVariable("name","Panda")
.build()
val response: Mono<ServerResponse> = helloHandler.handle(request).block()
// ??? verify ???
但是我没有找到足够的方法来观察响应的内部并验证其值。
您能建议如何与他们的HandleFunctions
分开测试RouterFunctions
吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。