How to test JSON Request using GSON API

HOME

In this tutorial, I will explain the testing of a JSON Payload using GSON API.

Refer to the below tutorials to understand how GSON works:-

Serialization – How to convert Java Object To JSON Object Using Gson API

Deserialization – How to create JSON Object to JAVA Object Using Gson API

Add below dependency to POM.xml to use Gson API.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

As we know, we can use toJson() to convert the JAVA objects to JSON Payload.

In the below example, I have created a POJO class with the name of EmployeeDetails. This class contains the data members corresponding to the JSON nodes and their corresponding getter and setter methods.

public class EmployeeDetails {

	// private variables or data members of pojo class
	private String name;
	private double salary;
	private int age;

	public String getName() {
		return name;
	}

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

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public int getAge() {
		return age;
	}

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

}

Below, will create a JSON payload and pass it as a request body to the Rest API.

	@Test
	public void createEmployee() throws IOException {

		// Just create an object of Pojo class
		EmployeeDetails emp = new EmployeeDetails();
		emp.setName("GsonTest");
		emp.setSalary(50000);
		emp.setAge(25);

		// Converting a Java class object to a JSON payload as string using Gson
		Gson builder = new GsonBuilder().setPrettyPrinting().create();
		String employeePrettyJsonPayload = builder.toJson(emp);
		System.out.println("Request");
		System.out.println(employeePrettyJsonPayload);
		System.out.println("=========================================");
		System.out.println("Response");

		// GIVEN
		given()
              .baseUri("http://dummy.restapiexample.com/api")
              .contentType(ContentType.JSON).body(emp)

		// WHEN
		.when()
               .post("/v1/create")

		// THEN
		.then()
              .assertThat().statusCode(200)
              .body("status", equalTo("success"))
			  .body("data.name", equalTo("GsonTest"))
              .body("data.salary", equalTo(50000))
			  .body("data.age", equalTo(25))
              .body("message", equalTo("Successfully! Record has been added."))
              .log().body();

	}
}

Output

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s