How to Test JSON Request Using GSON API

When it comes to testing APIs, verifying the correctness of the JSON request is as crucial as verifying the response. The GSON library in Java provides a simple way to convert Java objects to JSON and vice versa, making it an ideal tool for testing JSON requests in your API automation. In this blog post, we will walk through the steps of using the GSON API to test JSON requests effectively.

What is GSON?

GSON is a Java library developed by Google to handle the conversion of Java objects to JSON and vice versa. It provides simple methods to serialize (convert Java objects to JSON) and deserialize (convert JSON to Java objects) in a straightforward way.

Steps to Test JSON Request Using GSON API

Testing a JSON request involves creating a valid request in JSON format, serializing it into a Java object, and ensuring the object’s structure and content are correct before sending the request. Let’s break down how to use GSON for this task.

Step 1: Add GSON Dependency

To get started, you need to add the GSON dependency to your project. If you’re using Maven, you can include the following in your pom.xml file:

<dependency>

    <groupId>com.google.code.gson</groupId>

    <artifactId>gson</artifactId>

    <version>2.10.1</version>

</dependency>

If you're using Gradle, add this to your build.gradle file:

implementation 'com.google.code.gson:gson:2.10.1'

Step 2: Create Java Class to Represent JSON

For testing, you need a Java class that maps to the JSON request you intend to send. Let’s consider the example of sending a user object in the JSON format.

Example JSON Request:

{
  "username": "john_doe",
  "email": "john@example.com",
  "age": 30
}

Create the Java Class (Model):

public class User {
    private String username;
    private String email;
    private int age;

    // Getters and Setters
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

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

    public int getAge() {
        return age;
    }

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

This User class corresponds to the JSON request format, with fields for username, email, and age.

Step 3: Serialize Java Object to JSON

The next step is to convert your Java object (like the User object) into a JSON string. This is where GSON shines. You can do this with just one line of code:

import com.google.gson.Gson;


public class TestJsonRequest {

    public static void main(String[] args) {

        // Create a User object

        User user = new User();

        user.setUsername("john_doe");

        user.setEmail("john@example.com");

        user.setAge(30);


        // Convert the User object to JSON using GSON

        Gson gson = new Gson();

        String jsonRequest = gson.toJson(user);


        // Output the JSON string

        System.out.println(jsonRequest);

    }

}

Output:

{
  "username": "john_doe",
  "email": "john@example.com",
  "age": 30
}

The GSON toJson() method takes care of converting the Java object into a well-formed JSON string, ready to be sent as part of an API request.

Step 4: Testing the JSON Request

Once you've converted the object into JSON format, it’s time to test that the generated JSON matches the expected request structure. You can use assertions in your testing framework (e.g., JUnit, TestNG) to check that the JSON request is formed correctly.

Example Test Using JUnit:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class JsonRequestTest {

    @Test
    public void testJsonRequest() {
        // Create the User object
        User user = new User();
        user.setUsername("john_doe");
        user.setEmail("john@example.com");
        user.setAge(30);

        // Convert to JSON
        Gson gson = new Gson();
        String jsonRequest = gson.toJson(user);

        // Define the expected JSON string
        String expectedJson = "{\"username\":\"john_doe\",\"email\":\"john@example.com\",\"age\":30}";

        // Assert that the generated JSON matches the expected JSON
        assertEquals(expectedJson, jsonRequest);
    }
}

This test ensures that the Java object is correctly serialized into the expected JSON format.

Step 5: Send the JSON Request Using HTTP Client (Optional)

Once you’ve verified the structure of your JSON request, you can send it using any HTTP client (like HttpURLConnection, HttpClient, or libraries like RestAssured or HttpClient from Apache).

Here’s an example using HttpURLConnection:

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;


public class SendJsonRequest {

    public static void main(String[] args) throws Exception {

        // URL of the API endpoint

        String urlString = "http://example.com/api/user";

        URL url = new URL(urlString);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();


        // Set the HTTP method to POST

        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", "application/json");

        connection.setDoOutput(true);


        // Create the User object and convert it to JSON

        User user = new User();

        user.setUsername("john_doe");

        user.setEmail("john@example.com");

        user.setAge(30);


        Gson gson = new Gson();

        String jsonRequest = gson.toJson(user);


        // Send the JSON request body

        try (OutputStream os = connection.getOutputStream()) {

            byte[] input = jsonRequest.getBytes("utf-8");

            os.write(input, 0, input.length);

        }


        // Get the response code

        int responseCode = connection.getResponseCode();

        System.out.println("Response Code: " + responseCode);

    }

}

Followers