To test a GET API using Rest Assured in Java, you can follow the steps below. We'll walk through the process and test the endpoint:
API Endpoint: https://reqres.in/api/users
This API returns paginated user data in JSON format.
What is Rest Assured?
Rest Assured is a Java library for testing RESTful APIs. It provides a domain-specific language (DSL) for writing expressive and maintainable tests for APIs.
Basic Steps to Test GET API
- Add Rest Assured dependency in your
pom.xml
(if using Maven). - Set the Base URI.
- Send the GET request.
- Validate the Response (status code, headers, body).
- Log response (optional but useful for debugging).
Maven Dependency (pom.xml):
<dependencies> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.3.0</version> <scope>test</scope> </dependency> </dependencies>
Java Code to Test GET API
import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class GetUserApiTest { public static void main(String[] args) { // Step 1: Set Base URI RestAssured.baseURI = "https://reqres.in"; // Step 2: Send GET request and validate given() .log().all() // Logs the request details .when() .get("/api/users?page=2") // Endpoint .then() .log().all() // Logs the response details .assertThat() .statusCode(200) // Validate HTTP Status code .body("data", notNullValue()) // Validate response body contains 'data' .body("data.size()", greaterThan(0)) // Validate non-empty data .body("data[0].id", notNullValue()); // Validate user id present } }
Explanation of Code:
Line | Purpose |
---|---|
baseURI | Sets the base URL for the request. |
given() | Prepares request specification. |
log().all() | Logs all request and response data for visibility. |
get() | Triggers the GET request to the specified endpoint. |
then() | Begins response verification. |
statusCode(200) | Verifies the status code is 200 (OK). |
body(...) | Verifies the presence and contents of specific JSON fields. |
Sample JSON Output from API
{ "page": 2, "per_page": 6, "data": [ { "id": 7, "email": "michael.lawson@reqres.in", "first_name": "Michael", "last_name": "Lawson", ... } ] }
No comments:
Post a Comment