Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.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
如何获取javax.validation错误消息并在HTTP 400错误测试中检查这些消息?_Java_Spring Boot_Testing_Integration Testing_Javax.validation - Fatal编程技术网

如何获取javax.validation错误消息并在HTTP 400错误测试中检查这些消息?

如何获取javax.validation错误消息并在HTTP 400错误测试中检查这些消息?,java,spring-boot,testing,integration-testing,javax.validation,Java,Spring Boot,Testing,Integration Testing,Javax.validation,我在我的对象中使用javax.validation,在我的注释中有如下错误消息: @NotNull(message = "This name can't be a null parameter") private String name; @Test public void saveUser() throws Exception{ User user = builder.newUser(); getMockMvc().perform(post(URL_US

我在我的对象中使用javax.validation,在我的注释中有如下错误消息:

@NotNull(message = "This name can't be a null parameter")
private String name;
@Test
public void saveUser() throws Exception{
    User user = builder.newUser();

    getMockMvc().perform(post(URL_USER)
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(user)))
        .andExpect(status().isBadRequest());
        
}
当我在端点上使用@Valid时,java将检查我的验证并返回一个错误400,其中包含一个错误列表。在集成测试中,我检查如下错误:

@NotNull(message = "This name can't be a null parameter")
private String name;
@Test
public void saveUser() throws Exception{
    User user = builder.newUser();

    getMockMvc().perform(post(URL_USER)
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(user)))
        .andExpect(status().isBadRequest());
        
}

但是这个测试是不完整的,因为我没有检查错误消息。我需要一种方法来检查我的消息“这个名称不能是空参数”。我知道。。。我认为,这个消息在名为defaultMessage的参数中有一系列错误。有人能帮我吗?

您可以使用andReturn()将返回的消息分配给MvcResult,然后以字符串形式获得响应。之后,您可以解析(我在这里使用org.json)这个返回字符串并获得错误消息

final MvcResult mvcResult = getMockMvc().perform(post(URL_USER)
        .contentType(TestUtil.APPLICATION_JSON_UTF8)
        .content(TestUtil.convertObjectToJsonBytes(user)))
        .andExpect(status().isBadRequest())
        .andReturn();

final String resultString = mvcResult.getResponse().getContentAsString();

final JSONObject jsonObject = new JSONObject(resultString);
System.out.println(jsonObject.get("message"))