大多数时候,我们不是在普通的 JUnit
断言中添加注释,而是向断言添加一条消息,以解释为什么这是断言:
Person p1 = new Person("Bob");
Person p2 = new Person("Bob");
assertEquals(p1, p2, "Persons with the same name should be equal.");
现在,当涉及到 Spring Boot Web 环境中的端点测试时,我最终得到了这个:
// Bad request because body not posted
mockMvc.perform(post("/postregistration")).andExpect(status().isBadRequest());
// Body posted, it should return OK
mockMvc.perform(post("/postregistration").content(toJson(registrationDto))
.andExpect(status().isOk()));
有没有办法去除注释并向此类断言添加消息?因此,当测试失败时我会看到消息。
最佳答案
您可以提供自定义 ResultMatcher:
mockMvc.perform(post("/postregistration")
.content(toJson(registrationDto))
.andExpect(result -> assertEquals("Body posted, it should return OK", HttpStatus.OK.value() , result.getResponse().getStatus())))
mockMvc.perform(post("/postregistration"))
.andExpect(result -> assertEquals("Bad request because body not posted", HttpStatus.BAD_REQUEST.value(), result.getResponse().getStatus()));
解释:
截至今天,.andExpect()
方法只接受一个 ResultMatcher。当您使用 .andExpect(status().isOk())
时,StatusResultMatchers 类将以这种方式创建一个 ResultMatcher:
public class StatusResultMatchers {
//...
public ResultMatcher isOk() {
return matcher(HttpStatus.OK);
}
//...
private ResultMatcher matcher(HttpStatus status) {
return result -> assertEquals("Status", status.value(), result.getResponse().getStatus());
}
}
如您所见,该消息被硬编码为“状态”,并且没有其他内置方法来配置它。因此,尽管提供自定义 ResultMatcher 有点冗长,但目前可能是使用 mockMvc 的唯一可行方法。
关于java - 是否可以在使用 MockMvc 时添加断言消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62811386/