单元测试在执行过程中冻结



所以,我的问题来了——我正在尝试为我的应用程序进行单元测试。我有两个服务,我们称之为Foo和Bar,Foo只不过是Bar的代理。

因此,Foo服务的路由器看起来是这样的:

fun fooRoute(...) = coRouter {
. . .
GET("/something", fooHandler::findSomething)
. . .
}

向Bar服务发出请求的处理程序如下所示:

fun fooHandler(barClient: WebClient) {
. . .
suspend fun findSomething(request: ServerRequest): ServerResponse {
val response = barClient.get()
.uri(...)
.accept(...)
.awaitExchange()
. . .
return when (response.statusCode()) {
HttpStatus.OK -> {
ServerResponse
. . .
.bodyValueAndAwait(response.awaitBody<SomeType>())
}
else -> { 
ServerResponse
. . .
.buildAndAwait()
}
}
}
. . .
}

当我写这样的测试时:

. . .
private val barClient = mockk<WebClient>()
private val fooHandler = FooHandler(barClient)
private val fooRouter = FooRouter()
private val fooClient = WebTestClient.bindToRouterFunction(
fooRouter.fooRoute(
// mocks
. . .
fooHandler
)
).build()
@Nested
inner class FindSomething {
@Test
fun `returns OK`() = runBlocking {
val response = mockk<ClientResponse>()
val spec = mockk<WebClient.RequestHeadersUriSpec<*>>()
coEvery { response.awaitBody<SomeType>() } returns SomeType(...)
coEvery { spec.awaitExchange() } returns response
coEvery { barClient.get() } returns spec
fooClient
.get()
.uri(...)
.exchange()
.expectStatus().is2xxSuccessful
. . .
}
}

它只是永远冻结。。。嗯,我想这是因为它周围有一些协同游戏的魔力,但因为我还是这个游戏的新手,我不明白这里到底发生了什么。有什么帮助吗?

好吧,我根据这个答案编写了自己的交换函数,解决了这个问题。下面是我如何做到这一点的例子:

. . .
fun setUpBarClient(exchangeFunction: ExchangeFunction) {
barClient = barClient.mutate()
.exchangeFunction(exchangeFunction)
.build()
// recreate fooHandler & fooClient
}
@Nested
inner class FindSomething {
@Test
fun `returns OK`() {
// this one from org.springframework.web.reactive.function.client.ExchangeFunction
val exchangeFunction = ExchangeFunction {
Mono.just(
ClientResponse.create(HttpStatus.OK)
.header(...)
.body(...)
.build()
)
}
setUpBarClient(exchangeFunction)
fooClient
.get()
.uri(...)
.exchange()
.expectStatus().is2xxSuccessful
. . .
}
}

最新更新