How to remove keys from rest-assured ValidatableResponse and assert response with constant json string



  • In rest-assured test cases I am getting mentioned 'ValidatableResponse response' where I want to remove keys such as "updated_at", "deleted_at", "created_at" and "notice" and assert this object with expected string object with contains 'settings' using java 8 lambda expressions.

    { 
        "notice": "The Settings are updated successfully.",
        "settings": {
        "push_notification": {
            "enabled": true,
            "credentials": [{
                "key": "value"
            }],
            "service_name": "API Testing"
        },
        "created_at": "2019-05-04T14:52:32.773Z",
        "deleted_at": "false",
        "updated_at": "2019-05-07T11:23:22.781Z"
    }
    

    }

    Please help me with creating a common method which can be reuse for all test cases.



  • You can convert the JSON string into a JSON Object and then use

    <your_field>.remove()</code> and get the updated JSON back by converting it back to string.</p>
    
    <p>Below is a small example which demonstrates this: </p>
    
    
    

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.ArrayList;

    class Scratch {
    public static void main(String[] args) throws JSONException {
    String json = "{\n" +
    " "notice": "The Settings are updated successfully.",\n" +
    " "settings": {\n" +
    " "push_notification": {\n" +
    " "enabled": true,\n" +
    " "credentials": [\n" +
    " {\n" +
    " "key": "value"\n" +
    " }\n" +
    " ],\n" +
    " "service_name": "API Testing"\n" +
    " },\n" +
    " "created_at": "2019-05-04T14:52:32.773Z",\n" +
    " "deleted_at": "false",\n" +
    " "updated_at": "2019-05-07T11:23:22.781Z"\n" +
    " " +
    "}\n" +
    "}";

        // Create a JSON object from the json string
        JSONObject jsonObject = new JSONObject(json);
    
        // Get the object which needs to be manipulated
        JSONObject settings = jsonObject.getJSONObject("settings");
    
        // Add the attributes which needs to be removed as a list
        ArrayList<String> keysToRemove = new ArrayList<>();
        keysToRemove.add("created_at");
        keysToRemove.add("deleted_at");
        keysToRemove.add("updated_at");
    
        // Iterate for the all the keys to remove
        for (String key : keysToRemove) {
            // Remove the field from the JSON
            settings.remove(key);
        }
    
        System.out.println(jsonObject.toString());
    }
    

    }

    
    
    <p>Output:</p>
    
    
    

    {"settings":{"push_notification":{"credentials":[{"key":"value"}],"service_name":"API Testing","enabled":true}},"notice":"The Settings are updated successfully."}



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2