I am testing my API which I've created using Java and Spring Boot. I have a test method which returns me a 404 not found (which is intended) and I need to access the error message that is returned. Here's the response:
{
"timestamp": "2022-08-30T13:20:22.062 00:00",
"status": 404,
"error": "Not Found",
"message": "Name does not exist",
"path": "/mutualFundNav/sds"
}
I need to get the "message" variable and ensure the correct error message is displayed. I tried the following code:
@Test
void whenNonExistingNamePassedInThenReturn404() throws Exception {
mockMvc.perform(get(BASE_URL END_POINT "/Non existent name")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().is4xxClientError())
.andExpect(jsonPath("$.message", Matchers.is(NAME_NOT_FOUND)));
}
When I run this method, I do indeed get a 404 not found error like intended, but I'm unable to retrieve the error message. I get an error like this:
java.lang.AssertionError: No value at JSON path "$.message"
CodePudding user response:
Try this:
@Test
void whenNonExistingNamePassedInThenReturn404() throws Exception {
mockMvc.perform(get(BASE_URL END_POINT "/Non existent name")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().is4xxClientError())
.andExpect(jsonPath("$['message']", Matchers.is(NAME_NOT_FOUND)));
}