2

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]
Andrew Nolan
  • 1,987
  • 2
  • 20
  • 23

3 Answers3

3

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'

1

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()));
riyasvaliya
  • 745
  • 6
  • 8
0

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>

Andrew Nolan
  • 1,987
  • 2
  • 20
  • 23