Home > Mobile >  What is then().extract().body().jsonPath().getString("") doing?
What is then().extract().body().jsonPath().getString("") doing?

Time:12-03

I have this method in my Cucumber test:

public void validateError(String name, DataTable errorTable) {
  Map<String, String> error = errorTable.asMap(String.class, String.class);
  String result = then().extract().body().jsonPath().getString("");
  then().statusCode(Integer.parseInt(error.get("errorCode")));
  Assertions.assertThat(result).contains(error.get("errorMessage"));
}

It fails on then().extract().body().jsonPath().getString("") with:

Caused by: groovy.json.JsonException: Lexing failed on line: 1, column: 1, while reading 'B', no possible valid JSON value or punctuation could be recognized.

I'm trying to understand what then().extract().body().jsonPath().getString(""). Is it trying to extract the result from name? That would make sense as name is Bob in this case. I was expecting the line to extract the result from a json string though.

CodePudding user response:

The line then().extract().body().jsonPath().getString("") is trying to extract the result from the JSON response body using the JsonPath library. The empty string parameter passed to the getString() method indicates that it is trying to extract the value of the root element in the JSON response.

However, this line of code is likely causing the error because it is trying to extract a value from an empty string. Since there is no JSON response body in this case, the JsonPath library is unable to parse it and throws the groovy.json.JsonException.

To fix this error, you can either provide a valid JSON string to the getString() method or change the code to handle the case where there is no JSON response body.

CodePudding user response:

I don't understand how the code you provide compiles because I've not seen, then(), used liked that before, unless it's custom method you created. I've seen then() used in function programming style like the following.

Response response = given()
                .contentType(ContentType.JSON)
                .when()
                .get("/posts")
                .then()
                .extract().response();
  • Related