Skip to main content

RestAssured API Testing

RestAssured is a Java-based library that provides a domain-specific language (DSL) for API testing and automation. It simplifies the process of writing and executing tests for RESTful APIs, allowing developers to validate endpoints, perform assertions, and handle various aspects of API testing.

Key Features of RestAssured API Testing

  • Simplified Syntax: RestAssured offers an intuitive and concise syntax that makes it easy to write expressive tests for RESTful APIs.
  • Request Specification: It allows you to define request details such as base URI, headers, query parameters, and authentication methods.
  • Response Validation: RestAssured provides numerous methods for validating API responses, including assertions on status code, response body, headers, and more.
  • Chained Methods: RestAssured supports method chaining, enabling you to write tests in a fluent and readable manner.
  • Parameterization: It allows you to parameterize API requests and responses, facilitating the execution of the same test with different inputs.
  • Authentication and Authorization: RestAssured supports various authentication mechanisms such as basic, digest, OAuth, and more.
  • Error Handling: It provides built-in handling of common API errors and exceptions, allowing you to handle failures gracefully.
  • Integration with Testing Frameworks: RestAssured integrates seamlessly with popular testing frameworks like JUnit and TestNG, enabling comprehensive test suites and test reporting.
  • Configuration Options: RestAssured offers extensive configuration options to customize behavior, timeouts, logging, and more.

Example Usage

Here's an example of using RestAssured for API testing:

import org.testng.annotations.Test;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;

public class APITests {

@Test
public void testGetUser() {
given()
.baseUri("https://api.example.com")
.when()
.get("/users/1")
.then()
.statusCode(200)
.body("id", equalTo(1))
.body("name", equalTo("John Doe"));
}

@Test
public void testCreateUser() {
given()
.baseUri("https://api.example.com")
.contentType("application/json")
.body("{\"name\":\"Jane Smith\",\"email\":\"jane@example.com\"}")
.when()
.post("/users")
.then()
.statusCode(201)
.body("name", equalTo("Jane Smith"));
}
}

In the example above, two test methods (testGetUser and testCreateUser) are defined using RestAssured and TestNG. Each method sends API requests and uses assertions to validate the responses.

RestAssured provides a robust and feature-rich solution for API testing in Java, allowing developers to write concise, readable, and comprehensive tests for RESTful APIs.