如何使用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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...