WebFlux使用 Kotlin 的Type-Safe Builders定义了一个优秀的DSL,用于构建路由器。虽然语法非常简洁易读,但如何断言它返回的路由器函数 bean 配置正确并不明显,因为客户端代码几乎无法访问其属性。
假设我们有以下路由器:
@Configuration
class PingRouter(private val pingHandler: PingHandler) {
@Bean
fun pingRoute() = router {
accept(MediaType.APPLICATION_JSON).nest {
GET("/ping", pingHandler::handlePing)
}
}
}
我们想要断言,当一个请求/ping
与带有application/json
内容标头的路由匹配时,该请求将传递给我们的处理函数。
object PingRouterTest: Spek({
describe("PingRouter") {
lateinit var pingHandler: PingHandler
lateinit var pingRouter: PingRouter
beforeGroup {
pingHandler = mock()
pingRouter = PingRouter(pingHandler)
}
on("Ping route") {
/*
We need to setup a dummy ServerRequest who's path will match the path of our router,
and who's headers will match the headers expected by our router.
*/
val request: ServerRequest = mock()
val headers: ServerRequest.Headers = mock()
When calling request.pathContainer() itReturns PathContainer.parsePath("/ping")
When calling request.method() itReturns HttpMethod.GET
When calling request.headers() itReturns headers
When calling headers.accept() itReturns listOf(MediaType.APPLICATION_JSON)
/*
We call pingRouter.pingRoute() which will return a RouterFunction. We then call route()
on the RouterFunction to actually send our dummy request to the router. WebFlux returns
a Mono that wraps the reference to our PingHandler class's handler function in a
HandlerFunction instance if the request matches our router, if it does not, WebFlux will
return an empty Mono. Finally we invoke handle() on the HandlerFunction to actually call
our handler function in our PingHandler class.
*/
pingRouter.pingRoute().route(request).subscribe({ it.handle(request) })
/*
If our pingHandler.handlePing() was invoked by the HandlerFunction, we know we properly
configured our route for the request.
*/
it("Should call the handler with request") {
verify(pingHandler, times(1)).handlePing(request)
}
}
}
})