使用MockMvc和jsonPath()测试错误响应

Joh*_*ght 5 spring-mvc spring-test

我正在尝试使用以下方法测试Spring MVC控制器的错误响应

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())))
Run Code Online (Sandbox Code Playgroud)

但测试失败,例外: java.lang.IllegalArgumentException: json can not be null or empty 在第一个jsonPath断言上.

当我卷曲这个URL时,我得到以下内容:

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

有人可以帮我理解我做错了什么吗?

bor*_*ino 1

您编写了不正确的 JsonPath 表达式(更多信息链接),用于$根路径。在你的情况下它应该看起来像:

.andExpect(jsonPath('$.error', is("Not Found")))
.andExpect(jsonPath('$.timestamp', is(notNullValue())))
.andExpect(jsonPath('$.status', is(404)))
.andExpect(jsonPath('$.path', is(notNullValue())))
Run Code Online (Sandbox Code Playgroud)