如何在mockMvc中使用kotlin风格?

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

我用mockMvc进行了经典风格测试,它有效:

    val result = mockMvc.perform(
        post(path)
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(groupCreateDto)),
    ).andExpect(status().isBadRequest)
        .andReturn()    

我在这里认识到Kotlin有特定的风格,我决定重写:

val result = mockMvc.post(path) { contentType = MediaType.APPLICATION_JSON content = content().string(objectMapper.writeValueAsString(groupCreateDto)) }.andExpect { status().isBadRequest } .andReturn()
但它不起作用:

2023-10-03T13:19:34.536+03:00 ERROR 17912 --- [ Test worker] ***.RestExceptionHandler : JSON parse error: Unrecognized token 'org': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') MockHttpServletRequest: HTTP Method = POST Request URI = /api/v1/groups Parameters = {} Headers = [Content-Type:"application/json", Content-Length:"106"] Body = <no character encoding set> Session Attrs = {} Handler: Type = ****.MyGroupController Method = ****.MyGroupController#createGroup(GroupCreateRequestDto) Async: Async started = false Async result = null Resolved Exception: Type = org.springframework.http.converter.HttpMessageNotReadableException ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 500 Error message = null Headers = [Content-Type:"application/json"] Content type = application/json Body = {"code":500,"reason":"JSON parse error: Unrecognized token 'org': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')"} Forwarded URL = null Redirected URL = null Cookies = []
BRW 我在 

objectMapper.writeValueAsString(groupCreateDto)

 生成的字符串中没有 org
有什么想法吗?

spring-boot kotlin spring-mvc spring-boot-test mockmvc
1个回答
1
投票
问题是由 Kotlin 翻译中的这一行引起的:

content = content().string(objectMapper.writeValueAsString(groupCreateDto))
应该只是

content = objectMapper.writeValueAsString(groupCreateDto)
后一个代码将反映原始代码中的同一行。另一方面, 

content().string...

 构造创建了 
RequestMatcher
,这不是您想要的,因为此时您不在代码的断言部分。

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