spring-test MockMvc kotlin DSL缺乏异步支持?

问题描述 投票:1回答:1

spring-test增加了对MockMvc DSL的支持,可以在这里找到文档:https://docs.spring.io/spring/docs/5.2.0.M1/spring-framework-reference/languages.html#mockmvc-dsl

[当测试返回CompletableFuture(或任何其他异步结果类型)的控制器时,使用MockMvc的测试需要在声明主体之前对MvcResult执行asyncDispatch。可以在各种博客或stackoverflow问题中找到:

新的DSL似乎缺乏一种干净的方法。

例如,执行asyncDispatch需要以下代码:

@Test
internal fun call() {
    val mvcResult = mockMvc.get("/execute") {
        accept = APPLICATION_JSON
    }.andExpect {
        request { asyncStarted() }
    }.andReturn()
    mockMvc.perform(asyncDispatch(mvcResult))
        .andExpect(MockMvcResultMatchers.status().isOk)
        .andExpect(MockMvcResultMatchers.jsonPath("$.value", Is.`is`("test")))
}

我是否缺少能够启用此功能的东西,或者在DSL中还不能很好地支持?

更新:我尝试使用ResultActionsDsl上的扩展功能对此进行改进。

fun ResultActionsDsl.asyncDispatch(mockMvc: MockMvc):ResultActionsDsl {
    val mvcResult = andReturn()
    mockMvc.perform(MockMvcRequestBuilders.asyncDispatch(mvcResult))
    return this
}

这可以将测试写为:

@Test
internal fun call() {
    mockMvc.get("/execute") {
        accept = APPLICATION_JSON
    }.andExpect {
        request {
            asyncStarted()
        }
    }
    .asyncDispatch(mockMvc)
    .andExpect {
        status { isOk }
        jsonPath("$.value") { value("test") }
    }
}

我仍然觉得DSL可以开箱即用地支持。

spring spring-mvc spring-test
1个回答
0
投票

从Spring Framework 5.2.2和Spring Boot 2.2.2起,将使用以下语法支持此功能:

mockMvc.get("/async").asyncDispatch().andExpect {
    status { isOk }
}

请参见related issue以获取更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.