</>

Technology

Rest Assured

Difficulty

Intermediate

Interview Question

What is response time validation in Rest Assured and how do you assert it?

Answer

Response Time Validation in Rest Assured

Response time is a critical non-functional requirement for APIs. Rest Assured provides built-in support for measuring and asserting response times.

Method 1: BDD Style (Recommended)

Java
import static org.hamcrest.Matchers.lessThan;

@Test
public void testResponseTimeUnder2Seconds() {

    given()
        .when()
        .get("https://reqres.in/api/users")
        .then()
        .statusCode(200)
        .time(lessThan(2000L)); // response must be under 2000 milliseconds
}

Method 2: TimeUnit Version

Java
import java.util.concurrent.TimeUnit;

@Test
public void testResponseTimeInSeconds() {

    given()
        .when()
        .get("/api/users")
        .then()
        .time(lessThan(2L), TimeUnit.SECONDS); // under 2 seconds
}

Method 3: Extract and Assert Manually

Java
@Test
public void testResponseTimeManually() {

    long responseTimeMs = given()
                              .when()
                              .get("/api/users")
                              .timeIn(TimeUnit.MILLISECONDS);

    System.out.println("Response time: " + responseTimeMs + "ms");

    assertTrue(responseTimeMs < 2000,
        "Response time " + responseTimeMs + "ms exceeded 2000ms threshold");
}

Method 4: With Full Assertions

Java
@Test
public void testGetUsersPerformance() {

    given()
        .header("Authorization", "Bearer " + token)
        .when()
        .get("/api/users")
        .then()
        .statusCode(200)
        .contentType(ContentType.JSON)
        .time(lessThan(1000L))         // under 1 second
        .body("data.size()", greaterThan(0));
}

Method 5: Different SLAs by Endpoint Type

Java
// Search endpoint — can be slower
@Test
public void testSearchPerformance() {
    given().queryParam("q", "john")
           .when().get("/api/search")
           .then().time(lessThan(3000L)); // 3 seconds for complex search
}

// Simple GET — must be fast
@Test
public void testSimpleGetPerformance() {
    given().when().get("/api/users/1")
           .then().time(lessThan(500L)); // 500ms for simple lookup
}

SLA Guidelines

OperationTarget Response Time
Simple GET (by ID)< 200ms
GET list (with pagination)< 500ms
POST create< 300ms
Complex search/filter< 1000ms
File upload< 5000ms
Batch operations< 10000ms

Follow AutomateQA

Related Topics