Integrating RestAssured with JUnit 5 for API testing is a popular combination for writing clean, structured, and automated API tests in Java. Here's a detailed explanation and sample code:
What is RestAssured?
RestAssured is a Java-based library used to test RESTful APIs. It provides a domain-specific language (DSL) for making requests and validating responses.
What is JUnit 5?
JUnit 5 is the latest version of the popular unit testing framework for Java. It provides annotations, assertions, and other tools to write test cases.
Steps to Integrate RestAssured with JUnit 5
1. Add Maven Dependencies
<dependencies> <!-- RestAssured for API testing --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.4.0</version> <scope>test</scope> </dependency> <!-- JUnit 5 --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.10.0</version> <scope>test</scope> </dependency> <!-- JUnit 5 Engine --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.10.0</version> <scope>test</scope> </dependency> </dependencies>
Sample Test Code
package api; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.hamcrest.Matchers.*; import static io.restassured.RestAssured.*; public class SampleApiTest { @BeforeAll public static void setup() { // Set the base URI for all tests RestAssured.baseURI = "https://jsonplaceholder.typicode.com"; } @Test public void testGetPosts() { given() .when() .get("/posts") .then() .statusCode(200) .body("size()", greaterThan(0)); } @Test public void testGetPostById() { given() .when() .get("/posts/1") .then() .statusCode(200) .body("id", equalTo(1)) .body("userId", notNullValue()); } @Test public void testCreatePost() { String jsonBody = """ { "title": "foo", "body": "bar", "userId": 1 } """; given() .contentType(ContentType.JSON) .body(jsonBody) .when() .post("/posts") .then() .statusCode(201) .body("title", equalTo("foo")) .body("userId", equalTo(1)); } }
Explanation of Annotations
| Annotation | Description |
|---|---|
| @BeforeAll | Runs once before all test methods in the class. |
| @Test | Marks a method as a test case. |
Assertions and Features Used
statusCode(200): Asserts the HTTP status.body("id", equalTo(1)): Asserts the value in response body.greaterThan(0): Asserts list size.notNullValue(): Ensures the value is present.
How to Run
- In Eclipse/IntelliJ: Right-click the test class → Run as JUnit Test.
- Using Maven:
mvn test
No comments:
Post a Comment