(De)serializing POJOs in REST Assured

In this post, I’d like to demonstrate how you can leverage the ability of REST Assured to (de-)serialize Plain Old Java Objects (better known as POJOs) for more powerful testing.

As an example, we’ll use the following POJO representing a car and some of its properties:

public class Car {
	
	String make;
	String model;
	int year;
	
	public Car() {		
	}
	
	public Car(String make, String model, int year) {
		
		this.make = make;
		this.model = model;
		this.year = year;
	}
	
	public String getMake() {
		return this.make;
	}

	public void setMake(String make) {
		this.make = make;
	}
	
	public String toString() {
		return "My car is a " + this.year + " " + this.make + " " + this.model;
	}
}

Please note that I’ve removed the getters and setters for the other properties for brevity. Now, let’s create an instance of the car:

Car myCar = new Car("Aston Martin","DB9",2004);

Say we want to transmit the information stored in this object instance to a RESTful API, without having to map each individual property of our car to a corresponding field in the request. REST Assured supports this by allowing you to serialize the myCar object instance as follows:

@Test
public void testCarSerialization() {
				
	given().
		contentType("application/json").
		body(myCar).
	when().
		post("http://localhost:9876/carstub").
	then().
		assertThat().
		body(equalTo("Car has been stored"));
}

So, all you have to do is pass the object using body(). REST Assured will automatically translate this to the following request body:

{
    "make": "Aston Martin",
    "model": "DB9",
    "year": 2004
}

Neat, right? In this example, we serialized the car object to a JSON request, but REST Assured also allows you to serialize it to XML or HTML. Additionally, you can create custom object mappings as well. See this page in the REST Assured documentation for more information.

REST Assured also supports deserialization, meaning that we can easily transform a suitably formatted API response to a POJO instance:

@Test
public void testCarDeserialization() {
		
	Car myDeserializedCar = get("http://localhost:9876/carstub").as(Car.class);
		
	System.out.println(myDeserializedCar.toString());
	
	Assert.assertEquals("Check the car make", myDeserializedCar.getMake(), "Aston Martin");		
}

Note that http://localhost:9876/carstub points to a WireMock stub I’ve created to illustrate this example. The fact that our assertion is passing and that the console shows the following output when running the test tells us that deserialization has been successful:

My car is a 2004 Aston Martin DB9

You can download a Maven project containing all of the code I’ve used in the examples in this blog post here.

20 thoughts on “(De)serializing POJOs in REST Assured

  1. Pingback: Java Web Weekly, Issue 145 | Baeldung

  2. Pingback: Testing Bits – 10/2/16 – 10/8/16 | Testing Curator Blog

  3. I follow your instruction but i have an issue

    WHEN I post a request for authentication, the error occurs to say that: “java.lang.IllegalArgumentException: Cannot serialize because cannot determine how to serialize content-type application/x-www-form-urlencoded;charset=UTF-8”

    Here is my test method

    @Test
    public void authenticate()
    {
    AuthenDto authenDto = new AuthenDto(“username”,”password”,”false”,”Login”);
    given()
    .contentType(“application/x-www-form-urlencoded;charset=UTF-8”)
    .accept(“application/json, text/plain, */*”)
    .body(authenDto)
    .when()
    .post(“ENDPOINT”)
    .then()
    .statusCode(200);
    }

    • Not with the default included parsers. Don’t know if there’s an existing parser you could use, otherwise you’ll have to write and register your own I’m afraid.

  4. Team,

    I am facing same issue
    Cannot serialize because cannot determine how to serialize content-type application/x-www-form-urlencoded
    how can we fix this problem

  5. Pingback: REST Assured Serialization Object Mapper with JSON and XML

    • Unless you’re willing to write a custom equals() function, you’re stuck with the generic equals() method of the Java Object class, I think.

    • Hey Bas,

      Thanks for the nice article.

      Here is my scenario.

      We are currently managing the payload through POJO classes.
      We are following below approaches for building the payload.

      1) de-serialize the masterrequest.json and update the fields which are in context

      2) We are creating object for Pojo (fluent pojo) class and update all the fields when we want to use new data ( there are very few cases).

      we are depending helper methods to do the ‘2’ case.

      Is there any other or better way we can address this?

      Is there any way we can create pojos dynamically in java?

      Thanks in advance

      • Hey Ram, that’s very hard to tell without seeing your code. Is there anything in particular that’s not working well for you? If it ain’t broken, there’s no need to fix it 🙂

  6. Hi Bas,

    Thanks for the nice article. I have been using the Jackson recently and came across a situation where I have to send the null values/ empty property. Also I have set the @JsonIgnoreProperties(ignoreUnknown = true) and @JsonInclude(JsonInclude.Include.NON_NULL) at the class level. So basically I don’t want to set null values/ empty property for some tests and for negative tests its other way around. Is there any other way for this? Thanks

  7. Here is sample code:

    val requestBody: Any = object {
    val Name = “Name”
    val isActive = true
    }

    RestAssured.given().spec(rqSpec).body(createFilterRQ).`when`().post(myUrl)

    when capturing traffic with Fidler it’s found that the request body is:
    {
    name=”Name”
    Active=true
    }

    So the first letter is lower cased
    and the first phrase in name “is” is trimmed.

    Could propose any solution to overcome this problem?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.