0

I'm using the javax.validation in my objects and in my annotation I have the errors messages like this:

@NotNull(message = "This name can't be a null parameter")
private String name;

When I use the @Valid on my endpoint the java will check my validations and return a error 400 with a list of errors inside. And in my integration test I check the error like this:

@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());
        
}

But this test are incomplete, because I dont check the error message.I need a way to check my message "This name can't be a null parameter". I know... This message come in a array of errors in a parameter called defaultMessage I think. Someone can help me?

Lucas Alves
  • 23
  • 1
  • 9

1 Answers1

0

You can assign the returning message with andReturn() to MvcResult then you can get response as String. After, you can parse (I used org.json here) this returning string and get error message.

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"))