<- Back

This article is written in the context of RestAssured framework but core concepts can be applied to any kind of API testing or testing in general. In typical API testing, you want to send the JSON payloads in the request body and verify the JSON response. Here are some useful tips that may help you in your API testing project.

Map payloads to Classes

Create Classes for the request and response payloads. For example - If you want to send user payload, you can create simple class as shown below.

public class User {
    private String name;
    private String email;
    private int age;
    private Address address;

    public User() {}

    public User(String name, String email, int age, Address address) {
        this.name = name;
        this.email = email;
        this.age = age;
        this.address = address;
    }

    // Getter and setter methods for name
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // Getter and setter methods for email
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    // Getter and setter methods for age
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    // Getter and setter methods for address
    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public static class Address {
        private String street;
        private String city;
        private String state;
        private String zip;

        public Address() {}

        public Address(String street, String city, String state, String zip) {
            this.street = street;
            this.city = city;
            this.state = state;
            this.zip = zip;
        }

        // Getter and setter methods for street
        public String getStreet() {
            return street;
        }

        public void setStreet(String street) {
            this.street = street;
        }

        // Getter and setter methods for city
        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        // Getter and setter methods for state
        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        // Getter and setter methods for zip
        public String getZip() {
            return zip;
        }

        public void setZip(String zip) {
            this.zip = zip;
        }
    }
}

Sending request

When you need to send the JSON payload in the request, you do not have to use string representation of JSON. You can create an object of above class and directly use it as shown in below code. Restassured will convert the object to JSON string for you. This process is called as Serialization.

        RestAssured.given()
        .contentType(ContentType.JSON)
        .body(user)
        .post("/users");

Validating response

You can use built in assertion library or JSONPath to do validations. But there is a better way to validations using object based approach. You can convert the response into JSON object as shown in below example. Please make sure that Jackson JSON library dependency is added in maven for this code to work. What is happening here is that Restassured is using Jackson lib to convert the response into User object. This process is called as Deserialization.

        User actualUser  = response.body().as(User.class);

Alternatively you can also use JSONPath to deserialize the object. JSONPath is useful when you want to deserialize just the part of response. getObject method's first argument controls which part will be serialized. If you pass empty string, it will deserialize entire response. But if you pass specific property, only that property will be serialized.

        JsonPath jsonPath = response.jsonPath();
        User user = jsonPath.getObject("",User.class);

Once information is available in object, we can easily use assertions on object properties.

More on serialization

Most of the times, we do not want to full payload. e.g. In our User class example, let us say we want to send only name and email and skip rest of the fields. You can do this by adding @JsonInclude(JsonInclude.Include.NON_DEFAULT) annotation on top of User class. What this will do is that only those values will be serialized which we have initialized when creating object.

User user = new User();
user.setName("Sagar");
user.setEmail("[email protected]")

When this object is serialized, it will only contain name and email. Sometimes you need finer control over serialization process, in that case, you can override serialize method of JsonSerializer class. E.g. If you want custom serialization for age, you can use below code.

class AgeSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer age, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        try {
            if (age!=0)
                jsonGenerator.writeNumber(age + " years");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Please note that you will have annotate age field with below

@JsonSerialize(using = AgeSerializer.class)

More on Deserialization

By default, when the response is deserialized, each property in response is matched with field in the class and if field is not found, Exception "com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException." is thrown.

To avoid this exception, you can add below annotation to the User class.

@JsonIgnoreProperties(ignoreUnknown = true)

So what that means is that, even if there are 100 fields in response, only those fields will be deserialized which are found in the class and rest will be set to null or other uninitialized values.

Web development and Automation testing

solutions delivered!!