java - 是否可以在使用 MockMvc 时添加断言消息?

标签 java spring-boot junit mockmvc

大多数时候,我们不是在普通的 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/

相关文章:

java - 最终引用列表的 akka 不可变消息

java - 如何调用从 R 语言返回任何列表的 Java 方法?

java - 使用 hibernate 的一对多和一对一关系

java - jUnit 测试在 Eclipse 中工作,但在 ant 中失败 - java.lang.RuntimeException : Stub

java - 字段的 UML 域模型可见性

java - 如何在素数范围程序的输出中打印行号?

java - 如何解决 java.lang.ClassNotFoundException : org. aspectj.lang.ProceedingJoinPoint 异常?

spring-boot - USERAUTH 因 Github 和 Spring 云配置的私钥文件而失败

java - JUnit测试综合方法

java - 使用 JUnit 测试自定义注释是否存在于方法级别