response.jsonPath() 中的元素周围有方括号,如何检索字符串值? Rest Assured

huangapple go评论60阅读模式
英文:

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")));

huangapple
  • 本文由 发表于 2020年7月21日 22:29:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63016793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定