首页 文章

使用WebFlux WebTestClient和Kotlin键入干扰问题

提问于
浏览
1

我正在使用Spring Webflux和Kotlin为新应用程序构建原型 . Spring Webflux包含用于单元测试的WebTestClient . 根据文档,我应该能够像这样测试REST调用的结果:

@Test
fun getVersion_SingleResult_ContentTypeJson_StatusCodeOk_ContentEqualsVersion() {
    //given
    var version = Version("Test", "1.0")
    val handler = ApiHandler(version!!)
    val client = WebTestClient.bindToRouterFunction(ApiRoutes(handler).apiRouter()).build()

    //expect
    val response = client.get().uri("/api/version/").exchange()
    response.expectStatus().isOk
    response.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
    response.expectBody(Version::class.java).isEqualTo(version)
}

但是,我遇到了一些类型的干扰问题 . 问题在于'expectBody'和'isEqualTo'的结合 .

我得到的错误是:

Kotlin:类型推断失败:没有足够的信息来推断参数T in fun isEqualTo(p0:Version!):T!请明确说明 .

使用的方法具有以下签名:

<B> WebTestClient.BodySpec<B, ?> expectBody(Class<B> var1);

public interface BodySpec<B, S extends WebTestClient.BodySpec<B, S>> {
    <T extends S> T isEqualTo(B var1);
}

可悲的是,我遇到了我对泛型和Kotlin与Java之间差异的限制,这意味着我不确定如何指定它 .

编辑:就像我在下面说的那样,它在我使用 isEqualTo<Nothing>(version) 时编译 . 但是,当isEqualTo结束而没有失败时,这会导致NullPointerException . 这似乎是因为'isEqualTo'方法返回一个值,现在将其定义为'Nothing'类型 .

1 回答

  • 1

    这个已知的问题来自于已经在Spring JIRA上报告为SPR-15692的Kotlin类型推理限制(KT-5464)已经在Spring Framework 5.0.6 / Spring Boot 2.0.2中得到修复 . 确保通过编写 .expectBody<Foo>() 来使用Kotlin扩展 . 另见我创建的Kotlin中的the repository with concrete WebTestClient examples

相关问题