如何使用 Spring 的 WebTestClient 在 Kotlin 中检查字符串?

ctw*_*twx 1 spring unit-testing kotlin spring-boot webtestclient

我正在尝试使用 WebTestClient 检查返回字符串的控制器。但由于某种原因,我收到一个错误。

我使用 Kotlin,所以我尝试将我找到的 Java 示例应用到它,但我不知道如何正确地做到这一点。我错过了什么?

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class HelloResourceIT {

    @Test
    fun shouldReturnGreeting(@Autowired webClient: WebTestClient) {

        webClient.get()
                .uri("/hello/Foo")
                .accept(MediaType.TEXT_PLAIN)
                .exchange()
                .expectStatus()
                .isOk()
                .expectBody(String::class.java)
                .isEqualTo<Nothing>("Hello Foo!")
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用Stringjava.lang.String而不是Nothing我收到错误消息时:

类型参数不在其范围内。预期:没有!发现:字符串!

当我使用时,Nothing我会得到一个 NPE。

WebFlux WebTestClient 和 Kotlin已经存在类型干扰问题,但我使用的是特定类型。字符串在这里似乎不起作用。我缺少什么?

Tho*_*ood 6

看起来您没有使用被确定为变通方法的扩展功能。要使用它,请尝试按如下方式更新测试的最后两行:

webClient.get()
    .uri("/hello/Foo")
    .accept(MediaType.TEXT_PLAIN)
    .exchange()
    .expectStatus()
    .isOk()
    .expectBody<String>()
    .isEqualTo("Hello Foo!")
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常。

以供参考: