Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用MockMvc时是否可以添加断言消息?_Java_Spring Boot_Junit_Mockmvc - Fatal编程技术网

Java 使用MockMvc时是否可以添加断言消息?

Java 使用MockMvc时是否可以添加断言消息?,java,spring-boot,junit,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环境中的端点测试时,我的结

大多数情况下,我们不是在普通的
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()));

有没有办法去除注释并向此类断言添加消息?因此,当测试失败时,我将看到消息。

我发现
断言没有响应,因此改善了情况(根据我的要求):


您可以提供自定义结果匹配器:

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()
只接受一个结果匹配器。使用
.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());
    }
}


正如您所看到的,消息被硬编码为“Status”,并且没有其他内置方法来配置它。因此,尽管提供自定义结果匹配程序有点冗长,但目前可能是使用mockMvc唯一可行的方法。

一个想法是将测试方法称为failIfNoBodyPosted,这样当测试失败时,您就知道原因了。@marc-hmm,是的,我以前也想过,但我不喜欢它。测试一个有10个端点的控制器,其中每个端点有5-6个测试用例,我将得到60个具有类似名称的方法,我无法知道哪个方法引用哪个端点测试。就我个人而言,当涉及到(简单的)端点测试用例时,像脚本一样的代码是我的爱好。我不会将我的答案标记为已接受,以防有人有更好的(代码更少的方法)或者,
MockMvc
有一个我不知道的内置的东西。在您链接更多的
.andExpect()
子句时,这可能不够灵活。
public class StatusResultMatchers {
    //...
    public ResultMatcher isOk() {
        return matcher(HttpStatus.OK);
    }
    //...
    private ResultMatcher matcher(HttpStatus status) {
        return result -> assertEquals("Status", status.value(), result.getResponse().getStatus());
    }
}