π§ͺ Writing Your First API Test with RestAssured
π Introductionβ
Now that youβve set up your project and understand the given-when-then structure, itβs time to write your first API test. Writing tests is the core of API automation, and RestAssured makes it easy to send requests, validate responses, and ensure your APIs behave as expected.
In this section, weβll walk through the process of writing a simple API test step by step. By the end of this guide, youβll have a fully functional test that validates an API endpoint.
π― Step 1: Choose an API Endpointβ
Before writing a test, you need an API endpoint to test. For this example, weβll use ReqRes, a free, publicly available API for testing purposes.
- GET /api/users: Retrieves a list of users
π Step 2: Understand the Expected Behaviorβ
Request Detailsβ
- HTTP Method:
GET - URL:
https://reqres.in/api/users - Query Parameters: Optional (e.g.,
page=2)
Response Detailsβ
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "michael.lawson@reqres.in",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-image.jpg"
}
]
}
βοΈ Step 3: Write the Testβ
import io.restassured.RestAssured;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class FirstAPITest {
@Test
public void testGetUsers() {
RestAssured.baseURI = "https://reqres.in/api";
given()
.queryParam("page", 2)
.when()
.get("/users")
.then()
.statusCode(200)
.body("page", equalTo(2))
.body("data[0].first_name", equalTo("Michael"))
.body("data.size()", greaterThan(0));
}
}
π§© Step 4: Break Down the Testβ
Base URIβ
RestAssured.baseURI = "https://reqres.in/api";
Query Parametersβ
given()
.queryParam("page", 2);
Send Requestβ
when()
.get("/users");
Validate Responseβ
then()
.statusCode(200)
.body("page", equalTo(2))
.body("data[0].first_name", equalTo("Michael"));
βΆοΈ Step 5: Run the Testβ
Mavenβ
mvn test
Gradleβ
gradle test
Outputβ
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
π Step 6: Debugging and Loggingβ
given()
.log().all()
.when()
.get("/users")
.then()
.log().all();
β Best Practicesβ
-
Start Simple
-
Use Descriptive Test Names
-
Validate Edge Cases
-
Reuse Common Configurations
-
Log Requests and Responses
π Conclusionβ
Writing your first API test with RestAssured is a straightforward process. By following the steps outlined above, you can send requests, validate responses, and ensure your APIs behave as expected. In the next section, weβll explore more advanced topics like handling query and path parameters, headers, and request bodies to build even more robust API tests.