Search code examples
javaapitestingresponserest-assured

How to extract the Response of a RestAssured Call in Java to a class when the fields are wrapped in an object


I am using Rest Assured (Java) for API Testing an API. For a specific object, I created a class, lets name it "TestObject", which I pass on to POST Requests to create that object in the api. Now I want to use the GET Route to extract the object into another TestObject class for checks and further uses.

The problem: The Fields of my TestObject that I want to save are wrapped in a "content" object in the response JSON.

 "Content": {
        "CreatedAt": "2021-07-12T10:02:08.523Z",
        "UpdatedAt": "2021-07-12T10:02:08.523Z",
        "UUID": "5ba98999-f6a4-4ec1-8418-ed61022b5975"
 }

How can I extract and save the "Content" Object into my TestObject Class?

There is a method in RestAssured that directly extracts the Response to a class, but it then tries to save the Content directly as a variable, which I dont want.


Solution

  • Maybe you can use something like this by mapping to response directly to your pojo instead of mapping it to the RestAssured's Response:

    Create a POJO named TestObject

    public class TestObject {
    
        private ContentObject Content;
    
        public ContentObject getContent() {
            return Content;
        }
    
        @Override
        public String toString() {
            return "TestObject{" +
                    "Content=" + Content +
                    '}';
        }
    
        public static class ContentObject {
            private String CreatedAt;
            private String UpdatedAt;
            private String UUID;
    
            public String getCreatedAt() {
                return CreatedAt;
            }
    
            public String getUpdatedAt() {
                return UpdatedAt;
            }
    
            public String getUUID() {
                return UUID;
            }
    
            @Override
            public String toString() {
                return "ContentObject{" +
                        "CreatedAt='" + CreatedAt + '\'' +
                        ", UpdatedAt='" + UpdatedAt + '\'' +
                        ", UUID='" + UUID + '\'' +
                        '}';
            }
        }
    }
    

    Then you can use this like:

    TestObject testObject = when().get("/your/endpoint").then().extract().as(TestObject.class);
    System.out.println(testObject);
    System.out.println(testObject.getContent());