Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing an error response with MockMvc and jsonPath()

I'm trying to test an Spring MVC controller's error response with the following

this.mockMvc
    .perform(get("/healthChecks/9999"))
    .andExpect(status().isNotFound())
    .andExpect(jsonPath('error', is("Not Found")))
    .andExpect(jsonPath('timestamp', is(notNullValue())))
    .andExpect(jsonPath('status', is(404)))
    .andExpect(jsonPath('path', is(notNullValue())))

but the test is failing with the exception: java.lang.IllegalArgumentException: json can not be null or empty on the first jsonPath assertion.

When I curl this URL, I get the following:

{
  "timestamp": 1470242437578,
  "status": 200,
  "error": "OK",
  "exception": "gov.noaa.ncei.gis.web.HealthCheckNotFoundException",
  "message": "could not find HealthCheck 9999.",
  "path": "/healthChecks/9999"
}

Can someone please help me understand what I'm doing wrong?

like image 531
John Cartwright Avatar asked Aug 03 '16 16:08

John Cartwright


1 Answers

You write incorrect JsonPath expressions (For More Information LINK), use $ for root path. In your case it should look like:

.andExpect(jsonPath('$.error', is("Not Found")))
.andExpect(jsonPath('$.timestamp', is(notNullValue())))
.andExpect(jsonPath('$.status', is(404)))
.andExpect(jsonPath('$.path', is(notNullValue())))
like image 199
borino Avatar answered Nov 06 '22 10:11

borino