I am trying to extract values from JSON array with rest assured using jsonPath.
Example JSON Response:
{
"notices": [],
"errors": [
{
"code": "UNAUTHORIZED"
}
]
}
Current test is below:
@Test(dataProvider = "somePayLoadProvider", dataProviderClass = MyPayLoadProvider.class)
public void myTestMethod(SomePayload myPayload) {
Response r = given().
spec(myRequestSpecification).
contentType(ContentType.JSON).
body(myPayload).
post("/my-api-path");
List<String> e = r.getBody().jsonPath().getList("errors.code");
assertEquals(e, hasItem(MyErrorType.UNAUTHORIZED.error()));
}
however, i keep getting [] around my error code. I would just like the value.
java.lang.AssertionError: expected
[a collection containing "UNAUTHORIZED"] but found [[UNAUTHORIZED]]
Expected :a collection containing "UNAUTHORIZED"
Actual :[UNAUTHORIZED]
Apparently this was just me not using assert()
methods correctly.
Changed
assertEquals(e, hasItem(MyErrorType.UNAUTHORIZED.error()));
to
assertTrue(e.contains(MyErrorType.UNAUTHORIZED.error()));
The parsing of the json was done correctly to an ArrayList<String>
Alternatively you could specify the array index of 'errors' to remove the square brackets. ie:
List<String> e = r.getBody().jsonPath().getList("errors[0].code");
then you can return to using 'equals' rather than 'contains'
With rest-assured, you could also do chained assertions inline with the REST call like so:
given()
.spec(myRequestSpecification)
.contentType(ContentType.JSON)
.body(myPayload)
.post("/my-api-path") //this returns Response
.then() //but this returns ValidatableResponse; important difference
.statusCode(200)
.body("notices", hasSize(0)) // any applicable hamcrest matcher can be used
.body("errors", hasSize(1))
.body("errors", contains(MyErrorType.UNAUTHORIZED.error()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.