Search code examples
javajsonrest-assuredweb-api-testing

Validating UI against JSON response in RESTAssured/Java


I have a test scenario wherein the fields in my Web application are populated with data from json response.

e.g-> there is a field person id which when entered populates dozen other fields in UI ,make certain fields enabled or disabled depending upon other hidden field response in response. So, i have to match the json response with the displayed values in UI. The format of JSON request and response are like name value pair as in below:

 {
    "viewcode": 20,
    "actioncode": 40,
    "subcode": 0,
    "errorcode": 5,
    "username": "MANAGER",
    "database": "somedb",
    "data": {
        "personid": "070976",
        "hidden_first": "",
        "hidden_second": "",
        "hidden_third": ""
    }
}

I got to know about RestAssured and HTTP client library to achieve this but i am not sure on how to send the request part or retrieve the response because in many cases the responses are very big(more than 150 name value pair).

Below is what i have tried:

RestAssured.baseuRL="someurl"

RequestSpecification httpRequest=RestAssured.given();

Response response=httpRequest.request(Method.POST,"{{"viewcode":20, "actioncode":40, "subcode":0, "errorcode":5, "username":"MANAGER",  "database":"somedb", "data":{ "personid":"070976", "hidden_first":"", "hidden_second":"", "hidden_third":"" }}");

String responseBody=response.getBody.asString();

Now, I am getting error in Method.POST line, its showing syntax error also i am confused as to whether there are other approaches or not.


Solution

  • You need to escape some symbols (specially "):

    "{\"viewcode\":20, \"actioncode\":40, \"subcode\":0, \"errorcode\":5, \"username\":\"MANAGER\",  \"database\":\"somedb\", \"data\":{ \"personid\":\"070976\", \"hidden_first\":\"\", \"hidden_second\":\"\", \"hidden_third\":\"\" }}"
    

    In your code:

    String json = "{\"viewcode\":20, \"actioncode\":40, \"subcode\":0, \"errorcode\":5, \"username\":\"MANAGER\",  \"database\":\"somedb\", \"data\":{ \"personid\":\"070976\", \"hidden_first\":\"\", \"hidden_second\":\"\", \"hidden_third\":\"\" }}";
    httpRequest.body(json);
    Response response = httpRequest.post("/replace_with_your_endpoint");
    

    A complete list of characters to be escaped can be found here.