【发布时间】:2022-01-24 04:11:55
【问题描述】:
我正在使用 Spring 和 MockMvc。我正在为特定的控制器响应编写单元测试。它看起来像这样:
{
"errors": [
{
"error": "Bean validation failed.",
"message": "Bean: UserRegistrationDto. Class/field: userRegistrationDto. Constraint: SafePseudonym."
},
{
"error": "Bean validation failed.",
"message": "Bean: UserRegistrationDto. Class/field: addressLine1. Constraint: NotNull."
}
]
}
不保证数组errors 的顺序。这部分是因为 Spring 的SmartValidator。我想检查两个对象是否都在数组中,无论顺序如何。
这是我现在的代码:
mvc.perform(post("/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(validExampleUserRegistrationDtoBuilder().addressLine1(null).pseudonym("oyasuna").build())))
.andDo(result -> System.out.println(result.getResponse().getContentAsString()))
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.errors.length()").value(2))
.andExpectAll(
jsonPath("$.errors[0].error").value("Bean validation failed."),
jsonPath("$.errors[0].message").value("Bean: UserRegistrationDto. Class/field: addressLine1. Constraint: NotNull.")
)
.andExpectAll(
jsonPath("$.errors[1].error").value("Bean validation failed."),
jsonPath("$.errors[1].message").value("Bean: UserRegistrationDto. Class/field: userRegistrationDto. Constraint: SafePseudonym.")
);
【问题讨论】:
-
发布后不久,我找到了答案:stackoverflow.com/questions/26481059/…。
标签: spring spring-boot spring-mvc jsonpath