春季测试MockMvc kotlin DSL缺乏异步支持?

时间:2019-04-30 14:56:16

标签: spring-mvc spring-test

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需要以下代码:

ALTER PROCEDURE CopyReferenciasFromPDP
AS
BEGIN

    DECLARE @NumTurnos INT, 
            @NumPab INT,
            @AlcanceAbastecimento INT,
            @QtdMin INT,
            @QtdMax INT

    SET @NumTurnos = 3
    SET @NumPab = 6
    SET @AlcanceAbastecimento = 3
    SET @QtdMin = 3
    SET @QtdMax = 12

    CREATE TABLE #tempTable 
    (
        Id INT PRIMARY KEY,
        Referencia VARCHAR(15),
        UAP NVARCHAR(20),
        NumTurnos INT,
        NumPab INT,
        AlcanceAbastecimento INT,
        QtdMin INT,
        QtdMax INT
        UNIQUE (Id)
    )

    INSERT INTO #tempTable  
    SELECT
        ROW_NUMBER() OVER(ORDER BY Referencia ASC),
        Referencia,     
        UAP,
        @NumTurnos AS NumTurnos,
        @NumPab AS NumPAB,
        @AlcanceAbastecimento AS AlcanceAbastecimento,
        @QtdMin AS QtdMin,
        @QtdMax AS QtdMax
    FROM OPENQUERY(MACPAC, 
        'SELECT 
            A.RH6001 as Referencia, 
            A.RH6002 as UAP
        FROM AUTO.D805DATPOR.TRP060H AS A       
        WHERE (A.RH6001 Not Like ''FS%'')
        AND A.RH6030 <> 0') 


    INSERT INTO 
        Parametros
    SELECT 
        Referencia, 
        UAP,        
        NumTurnos,
        NumPab,
        AlcanceAbastecimento,
        QtdMin,
        QtdMax
    FROM 
        #tempTable M
    WHERE
        NOT EXISTS 
        ( 
            SELECT * FROM Parametros P  
            WHERE M.Referencia = P.Referencia 
            AND M.UAP = P.UAP
        )

    DROP TABLE #tempTable
END

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

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

@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")))
}

这使得将测试编写为:

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

我仍然觉得DSL可以立即支持。

1 个答案:

答案 0 :(得分:0)

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

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

有关更多详细信息,请参见related issue