API Testing with Rest-Assured: Benefits, Methods, and Implementation

API Testing with Rest-Assured

API Testing with Rest-Assured

What is API Testing?

API Testing is a type of software testing aimed at verifying the functionality and reliability of an Application Programming Interface (API). APIs are crucial as they define the methods through which different components of an application can communicate, allowing for data exchange and function sharing. During the API testing process, requests are submitted to the API, responses are obtained, and the behavior of the API is evaluated against predefined criteria. Key aspects checked include the accuracy and format of the data, HTTP status codes, and the presence of any error codes.

Advantages of API Testing


Accelerated Bug Detection: API testing outpaces manual testing significantly, particularly when your application has many features to be tested. Automated test suites deliver results in a compact timeframe, helping to ensure the application operates as intended.

Increased Team Capacity: API tests can run around the clock, optimizing the use of limited testing resources.

Faster Release Times: API testing reduces the time between feature integration and market launch.

Enhanced Test Coverage: API testing allows for efficient tracking and management of test results. It provides insights into defects, exceptions, and performance issues, enabling teams to promptly address and resolve any identified issues.

What is Rest-Assured?

Rest Assured is a Java library used to verify the REST APIs. This library functions as a headless client to interact with RESTful web services.

What Are the Benefits of Rest-Assured Testing Automation

Ease of Use

Rest-Assured offers a simple and intuitive syntax for making API requests and validating responses, making it easy to write and maintain test scripts.

Data Format Support

Rest-Assured supports various data formats such as JSON and XML, allowing you to work seamlessly with different types of API responses.

Parallel Execution

Rest-Assured empowers your testing strategy by allowing you to run multiple test cases simultaneously. This parallel execution capability optimizes test suite performance, reduces testing time, and enhances overall efficiency.

Readable Test Reports

Rest-Assured reports make it easy to understand the results of API tests.
These reports provide important information such as the main test result (pass or fail), request and response data, and any errors or exceptions that occurred during testing. The presentation of test results is clear and organized, which simplifies the debugging process. This enables testers to quickly identify issues and promotes collaboration between testers and developers.

Easy CI/CD Integration

Rest-Assured seamlessly integrates with CI/CD pipelines. Rest-Assured’s compatibility with popular CI/CD tools like Jenkins ensures that your API tests are automatically executed whenever there are code changes or deployments. This integration allows for early detection of issues and ensures that your APIs remain reliable throughout the development lifecycle.

How to get started with Rest-Assured

Choosing a Test Project

Let’s begin by selecting a Test Project (**https://petstore.swagger.io/**) and focusing on covering the four main routes: GET, POST, PUT, DELETE.

Configuring Dependencies in Your Java Maven Project Setup

1. Start by setting up your project with Java11 and Maven;
2. Add the following dependencies to your pom.xml file, which can be found in the Maven Repository:
2.1. JUnit5: This will be used for writing and executing your test cases;
2.2. Rest-Assured: This is our main framework for API testing;
2.3. Lombok and Jackson: These libraries are used for serializing and deserializing JSON data;
2.4 Data Faker: It provides an easy way to generate test data;
2.5 Allure Report: You can use this to generate detailed reports after running your tests.

Creating Test Classes and Writing Test Cases

1. Create a BaseTest class where you’ll set the base URL of your service and enable logging of requests and responses for easier debugging. Subsequently, test classes will extend this BaseTest class.

2. Create a PetController class using Rest-Assured that contains four routes to interact with the pet store’s API. These routes include methods for creating, retrieving, updating, and deleting pet records.

 

3. Create the **Pet** class using Lombok to represent pet data based on the fields defined in the Swagger Specification. This class serves as a data model for working with pet information, making it easier to serialize and deserialize data when interacting with the API.

4. Create the PetSteps class, which extends the PetController class. In this class, we implement methods that call our HTTP endpoints, perform assertions on the response’s status code, and deserialize the response data into our Pet model. This class plays a crucial role in structuring our API test scenarios and ensuring that the API behaves as expected.

5. Create the PetTests class, which extends from the BaseClass. In this class, we’ll develop a suite of test cases for our API. We’ll include three positive tests, which verify the expected behavior of the API when everything works as intended, and one negative test to check how the API handles erroneous requests or unexpected situations.

5.1 The first test case focuses on the **Create New Pet** functionality using the HTTP POST method. In this test, we will send a request to the API to add a new pet to the system and verify that the pet is successfully created with the expected attributes.

5.1.1. First, we’ll create a PetDTO class that will represent the pet data, including all the required fields. To generate realistic test data for this class, we’ll utilize the Faker library and follow the Builder pattern. This will allow us to easily populate the PetDTO object with mock data for our test cases.

5.1.2. Then, we will send a POST request to the server in order to create a new pet.

5.1.3. Then, call the ‘verifyPetIsCreated’ function to ensure that the response matches the request.

5.1.4. In real-world scenarios, it’s a good practice to clean up test data. Therefore, after the test, we call the deletePet function to remove the created Pet.

5.2 The second test focuses on Getting all Pets by selected status using the GET method. We have defined a PetStatus enum with three statuses: AVAILABLE, PENDING, SOLD. We will cover all three cases in this test.

5.2.1. First, create a test class that uses the @EnumSource, @ParameterizedTest annotations from JUnit5 to parameterize this method using our Enum and provide one property, petStatus, to our function.

5.2.2. Then, Create pets as a precondition step.

5.2.3. Then, Send the GET request to the server to retrieve the list of pets.

5.2.4. Finally, call the verifyGetAllPetByStatus function to verify that the response contains only pets with the selected PetStatus.

Generating and Managing Test Results with Allure Report

To view the test results after running the tests, you can use allure serve command, which opens a local link in your browser displaying a report. In this report, you can manage test results, including attaching requests and responses for each test.

To Sum Up

Rest-Assured is an exceptional tool for automating API tests. Its user-friendly syntax and robust features facilitate the development of automated tests, leading to swift and efficient test script creation. Rest-Assured instills confidence in testers, empowering them to validate the functionality, reliability, and compliance of APIs, thus becoming an indispensable asset in the software testing domain.

Bug Free App – A Myth or Reality?

There’s a reason why the global bug tracking software market expected to reach $601.64 million by 2026. And the reason is very simple – because every digital product has bugs and requires maintenance. Think of it like this: your digital product is like a house. Imagine that you built a house following all standards, using […]

Zorian Fedoryga Avatar
Zorian Fedoryga

27 Jan, 2023 · 6 min read

End-to-End Automated Testing with Cypress

Software development is getting more complicated, so every QA team needs to concentrate on boosting test coverage. To achieve this, it’s essential to use a variety of testing types, such as integration testing, system testing, performance testing, and end-to-end testing, depending on the complexity of your software application and requirements. In case end-to-end testing sounds […]

Marian Turchyn Avatar
Marian Turchyn

8 Sep, 2023 · 7 min read

Selenium vs. Playwright: A Comparative Analysis of Automated Web App Testing Tools

Selenium is widely recognized for its essential role in web testing. However, it is also known for challenges associated with unpredictable selectors, which can lead to inconsistent and unreliable tests. The name “Selenium” is a playful jab at a competitor named “Mercury,” hinting at the idea that just as selenium can counteract mercury poisoning, Selenium […]

Andrii Lesyshyn Avatar
Andrii Lesyshyn

20 Mar, 2024 · 6 min read