Answer
Serialization and Deserialization in API Testing
In the context of API testing, these terms refer to converting Java objects into JSON (or XML) format and vice versa. This is essential when sending and receiving data to and from APIs, as most APIs use JSON or XML as their data format.
Serialization
Deserialization
Example Scenario
Consider an API with these endpoints:
- ✓
POST /api/person— create a new person - ✓
GET /api/person/{id}— retrieve a person''s details
Step 1: Create POJO Class
public class Person {
private String name;
private int age;
public Person() { }
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
Step 2: POST Request with Serialization
public class ApiTest {
@BeforeClass
public void setup() {
RestAssured.baseURI = "http://example.com/api";
}
@Test
public void testCreatePerson() {
Person person = new Person("John Doe", 30);
Response response = given()
.contentType(ContentType.JSON)
.body(person) // ← Serialization happens here
.when()
.post("/person");
assertEquals(response.getStatusCode(), 201);
}
}
In testCreatePerson, the Person object is converted into a JSON string using the Jackson library (handled internally by REST Assured) when passed to .body().
Step 3: GET Request with Deserialization
@Test
public void testGetPerson() {
Response response = given()
.when()
.get("/person/1");
assertEquals(response.getStatusCode(), 200);
Person person = response.as(Person.class); // ← Deserialization happens here
assertEquals(person.getName(), "John Doe");
assertEquals(person.getAge(), 30);
}
In testGetPerson, the JSON response is converted back into a Person object using .as(Person.class).
Jackson Library Requirement
Add to pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
