我用mockMvc进行了经典风格测试,它有效:
val result = mockMvc.perform(
post(path)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(groupCreateDto)),
).andExpect(status().isBadRequest)
.andReturn()
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 有什么想法吗?
content = content().string(objectMapper.writeValueAsString(groupCreateDto))
应该只是
content = objectMapper.writeValueAsString(groupCreateDto)
后一个代码将反映原始代码中的同一行。另一方面, content().string...
构造创建了
RequestMatcher
,这不是您想要的,因为此时您不在代码的断言部分。