Applying API Testing Frameworks: Real-World Example with REST Assured for a Product Service



This content originally appeared on DEV Community and was authored by Juan Brendon Luna Juarez

Applying API Testing Frameworks: Real-World Example with REST Assured for a Product Service

APIs are the backbone of many modern applications, enabling communication between different systems and services. Therefore, ensuring that an API works correctly is crucial for software quality. In this article, we will explore how to apply the REST Assured framework to automate tests on a RESTful service that manages products.

What is REST Assured?

REST Assured is a Java-based testing framework designed to simplify testing of RESTful APIs. Its fluent syntax allows writing readable and expressive tests that validate HTTP responses, JSON or XML bodies, headers, and more. It integrates easily with testing frameworks like JUnit or TestNG, making it ideal for continuous integration pipelines.

Key Advantages of REST Assured

  • Intuitive and expressive syntax.
  • Easy validation of status codes, headers, and response bodies.
  • Support for authentication, parameters, and various HTTP methods.
  • Integration with common Java tools.
  • Active community and good documentation.

Limitations

  • Requires basic knowledge of Java.
  • No graphical user interface; tests are written in code.

Case Study: Product Management API

Imagine we work with an API that manages a product catalog for an online store. The API includes several endpoints, such as:

  • GET /products/{id}: Retrieves information about a specific product.
  • POST /products: Creates a new product.
  • PUT /products/{id}: Updates an existing product.
  • DELETE /products/{id}: Deletes a product.

In this article, we will focus on testing the GET /products/{id} endpoint to ensure it returns correct information and meets expected standards.

Testing Objectives

We want to validate that:

  • The HTTP response status code is 200 when the product exists.
  • The JSON body contains the fields id, name, price, category, and inStock.
  • The name field is a non-empty string.
  • The price field is a positive number.
  • The category field belongs to a predefined list of valid categories.
  • The inStock field is a boolean.
  • The Content-Type header is application/json.

REST Assured Test Code Example

Below is a complete Java example using REST Assured and JUnit to validate the endpoint:

import static io.restassured.RestAssured.;
import static org.hamcrest.Matchers.;
import org.junit.BeforeClass;
import org.junit.Test;

public class ProductApiTest {

@BeforeClass
public static void setup() {
baseURI = “https://api.example-store.com“;
}

@test
public void testGetProductById_ValidProduct() {
int productId = 101;

given()
    .pathParam("id", productId)
.when()
    .get("/products/{id}")
.then()
    .statusCode(200)
    .contentType("application/json")
    .body("id", equalTo(productId))
    .body("name", allOf(notNullValue(), not(isEmptyString())))
    .body("price", greaterThan(0.0f))
    .body("category", isOneOf("Electronics", "Books", "Clothing", "Home", "Sports"))
    .body("inStock", anyOf(equalTo(true), equalTo(false)));

}

@test
public void testGetProductById_ProductNotFound() {
int invalidProductId = 99999;

given()
    .pathParam("id", invalidProductId)
.when()
    .get("/products/{id}")
.then()
    .statusCode(404)
    .body("error", equalTo("Product not found"));

}
}

Detailed Explanation

  • @BeforeClass and baseURI: Sets up the base URI for all requests.
  • testGetProductById_ValidProduct():
    • Uses pathParam to inject the product ID into the URL.
    • Validates the status code is 200.
    • Confirms the Content-Type header is application/json.
    • Checks that the id field in the response matches the requested ID.
    • Ensures the name field is neither null nor empty.
    • Validates that the price is a positive number.
    • Verifies the category is one of the allowed values.
    • Confirms inStock is a boolean value (true or false).
  • testGetProductById_ProductNotFound():
    • Tests with an invalid product ID to ensure the API returns a 404 status and an appropriate error message.

Why Use REST Assured?

REST Assured allows you to automate API tests easily and robustly, with a clear syntax that promotes maintainable code. By integrating with JUnit, you can run these tests within CI/CD pipelines to ensure continuous software quality.

Recommended Next Steps

  • Extend tests to other endpoints (POST, PUT, DELETE).
  • Add validations for authentication and authorization.
  • Integrate with automated reporting tools to visualize results.
  • Combine with mocking tools for isolated testing environments.


This content originally appeared on DEV Community and was authored by Juan Brendon Luna Juarez