英文:
response.jsonPath() has square brackets around the element, how do I retrieve the string value? Rest Assured
问题
[
{
"id": "1111",
"type": "Sale",
"name": "MyNameTest",
"shortDescription": "Sale a"
}
]
当我尝试使用 "Rest Assured" 来断言结果时,名称值总是被包裹在方括号中 []。
final String returnedAttributeValue = response.jsonPath().getString("name");
Assert.assertEquals(returnedAttributeValue, "MyNameTest");
因此,测试失败,期望值为 "MyNameTest",但实际值为 "[MyNameTest]"。
有人可以告诉我如何解决这个问题吗?
英文:
I have an HTTP response body that looks that this when I make a GET request:
[
{
"id": "1111",
"type": "Sale",
"name": "MyNameTest",
"shortDescription": "Sale a"
}
]
When I try to assert the results with "Rest Assured", the name value is always wrapped in square brackets [].
final String returnedAttributeValue = response.jsonPath().getString("name");
Assert.assertEquals(returnedAttributeValue, "MyNameTest");
So the test fails with Expected "MyNameTest", but was "[MyNameTest]"
Can any one tell me how to resolve this?
答案1
得分: 3
你正在访问数组内的值,因此使用 name[n]
final String returnedAttributeValue = response.jsonPath().getString("name[0]");
Assert.assertEquals(returnedAttributeValue, "MyNameTest");
英文:
You are accessing values within an array, so use name[n]
final String returnedAttributeValue = response.jsonPath().getString("name[0]");
Assert.assertEquals(returnedAttributeValue, "MyNameTest");
答案2
得分: 0
另一种检查数组内容的可能解决方案是使用 org.hamcrest.Matchers.contains
:
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.hamcrest.Matchers.contains;
response
.andExpect(jsonPath("$name", contains("MyNameTest")));
英文:
Another possible solution for checking the content of an array, you could use org.hamcrest.Matchers.contains
:
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.hamcrest.Matchers.contains;
response
.andExpect(jsonPath("$name", contains("MyNameTest")));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论