Reputation: 2107
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]
Upvotes: 2
Views: 6205
Reputation: 825
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()));
Upvotes: 1
Reputation: 31
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'
Upvotes: 3
Reputation: 2107
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>
Upvotes: 0