Automating POST Request using Rest Assured - Part 2
In the previous post, we learned about automating a POST request by sending a string in the body method. In this post, we will focus on automating a POST request by sending an object in the body method instead of string.
The reason behind sending an object in body method is that sending a string with large number of parameter can become tedious and updating a string having n number of parameters may become time consuming. Hence, it is always recommended to send an object in body method.
Now lets look at an example of automating POST request using Rest Assured.
public class Posts { public String id; public String title; public String author; public void setId (String id) { this.id = id; } public void setTitle (String title) { this.title = title; } public void setAuthor (String author) { this.author = author; } public String getId () { return id; } public String getTitle () { return title; } public String getAuthor () { return author; } }
In the above Post class, we have created getter and setter methods of the parameters that we need to pass to the body method.
Now we will send the POST request
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.restapiclass.Posts;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class PostRequestTest {
@BeforeClass
public void setBaseUri () {
RestAssured.baseURI = "http://localhost:3000";
}
@Test
public void sendPostObject () {
Posts post = new Posts();
post.setId ("3");
post.setTitle ("Hello India");
post.setAuthor ("StaffWriter");
given().body (post)
.when ()
.contentType (ContentType.JSON)
.post ("/posts");
}
}
In the setBaseUri method, We are simply setting the default URI to use in all of our tests. Now when we write out a test that calls an API (as we will do in the next step), we don’t have to type in the full address of the API. In this case, the baseUri is http://localhost:3000.
In the sendPostObject method, we create an object of Posts class and then setID, setTitle and setAuthor using the setter methods of Posts class.We then start with Given method and specify the data to be added as an object of post class in the body method. Under When we simply add a check ‘contentType(ContentType.JSON)‘ to make sure that the response we get is in JSON format and under POST method we specify the path '/posts'.
So the data related to id :3 is added to db.json file.
In the next post, we will learn about how to send a PUT Request using Rest Assured.
Comments
Post a Comment