In this blog entry, we are going to look at how to write a REST Assured Post test. We are going to look at an example API that expects an object. The API will then process that object using POST. Let’s take a look at the example API:

@RequestMapping(value = "/person", method = RequestMethod.POST, consumes="application/json", produces = "application/json")
public Person person(@RequestBody Person persons) {
    return new Person(persons.getName(), persons.getAge());
}

The endpoint above does four main things:

  • Performs a Post
  • Expects an Object of type Person to be passed in
  • Expects the data to be of type json to be passed in
  • Produced a json

In order to use the endpoint above, we need to update our existing POJO. We will need to add an “age” integer alongside a constructor. Doing this will allow use to pass in both names and ages:

public class Person {

    String name;
    int age;

    Person() {}

    Person(String name) {
        this.name = name;
        this.age = 10;
    }

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

    public String getName() {
        return this.name;
    }

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

    public int getAge() {
        return this.age;
    }
}

An int “age” member variable has been added to the POJO above with an additional third constructor. This stops our current tests from breaking as we did not need to modify the signature of our second constructor. We have also hardcoded the age in the second constructor which only accepts a String.

Now that we have an update POJO and a new endpoint, let’s write a test for it. Our test will need to be able to provide what type of content we are passing in. It will also need to be able to pass in an object of type Person. We will also need to think about how we will perform any assertions on the returned data:

@Test
public void shouldGetPersonObject() {
    given()
        .contentType("application/json")
        .body(new Person("qashahin", 25))
    .when()
        .post("/person")
    .then()
        .body("name", is("qashahin"))
        .body("age", is(25));
}

The updated test above now performs a REST Assured Post test. It also passes in a JSON and performs multiple assertions on the JSON output. We also pass in a Person object.

In this article we have looked at how we can write a REST Assured test for a POST endpoint. We have looked at how to pass in an Object and assert on the many variables that an endpoint can return.

Please follow and like us:

Leave a Reply