To Check Response Time using Rest Assured



In the previous post, we studied about automating delete request using Rest Assured. In this post, we will learn about checking the response time of REST API. I would highly recommend to read previous tutorials before reading this one.

Response Time is nothing but the total time taken to get REST API response. Let's look at the example to check the response time of API installed on our local system using Rest Assured.

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.lessThan;


public class VerifyResponseTime {

@BeforeClass
  public void setBaseUri () {

    RestAssured.baseURI = "http://localhost:3000";
  }

@Test
 public void responseTime ()  {
   given()
   .when ()
   .get ("/posts")
   .then ()
   .time (lessThan (10l));
 }
}

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 responseTime method, we start with Given method and under When we specify the GET method in which we mention the path of URI which we will hit. Under Then we simply add a check ‘time (lessThan (10l))‘ to make sure that the response we get should take time less than 10 milliseconds.

For time method, we need to add following import:
static org.hamcrest.Matchers.lessThan;

In above example, the test will fail since the time taken to get the response will be more than 10 milliseconds i.e 1029 milliseconds


Now let's look at an example where we add the check in which we should get an API response before 1050 seconds.

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.lessThan;
public class VerifyResponseTime { @BeforeClass public void setBaseUri () { RestAssured.baseURI = "http://localhost:3000"; } @Test public void responseTime () { given() .when () .get ("/posts") .then () .time (lessThan (1050l)); } }


In the above case, the test will pass as the time taken by API will be less than 1050 milliseconds. In the next post, we will learn about  Using RequestSpecBuilder in Rest Assured

Comments

Popular posts from this blog

Extracting an XML Response with Rest-Assured