[英]How to get error message from response body using jsonPath
I am testing my API which I've created using Java and Spring Boot.我正在测试我使用 Java 和 Spring 引导创建的 API。 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.
我有一个测试方法,它返回一个 404 未找到(这是有意的),我需要访问返回的错误消息。 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.当我运行这个方法时,我确实得到了一个 404 not found 错误,但我无法检索错误消息。 I get an error like this:
我收到这样的错误:
java.lang.AssertionError: No value at JSON path "$.message"
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)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.