To integrate RestAssured with JUnit 4 for API testing, you can follow these steps:
Overview
RestAssured: A Java DSL for testing REST services.
JUnit 4: A popular unit testing framework for Java.
Integration Workflow
- Add RestAssured and JUnit 4 dependencies.
- Write test cases using JUnit 4 annotations (
@Test,@Before, etc.). - Use RestAssured to make HTTP requests and validate responses.
1. Maven Dependencies
<dependencies> <!-- RestAssured --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.4.0</version> <scope>test</scope> </dependency> <!-- JUnit 4 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!-- JSON path (optional but useful) --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>json-path</artifactId> <version>5.4.0</version> </dependency> </dependencies>
2. Simple GET API Test Example
import io.restassured.RestAssured; import io.restassured.response.Response; import org.junit.Before; import org.junit.Test; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class APITest { @Before public void setup() { RestAssured.baseURI = "https://jsonplaceholder.typicode.com"; } @Test public void testGetUser() { given(). log().all(). when(). get("/users/1"). then(). log().all(). assertThat(). statusCode(200). body("id", equalTo(1)). body("username", notNullValue()); } @Test public void testGetInvalidUser() { given(). log().all(). when(). get("/users/9999"). then(). log().all(). assertThat(). statusCode(404); } }
3. Explanation of Code
| Section | Description |
|---|---|
| @Before | Sets the base URI for all API requests. |
| given() | Prepares the request (params, headers, etc.). |
| when() | Specifies the request type (GET/POST/PUT/DELETE). |
| then() | Asserts the response: status, body content, etc. |
| log().all() | Logs request/response details to console (for debugging). |
4. Run the Tests
You can run these tests using:
Eclipse/IntelliJ (right-click → Run as JUnit Test)
Maven CLI:
mvn test
5. Important Points:
Externalize base URLs using config files or environment variables.
Use
@BeforeClassfor expensive setups.Use assertions to validate headers, response time, etc.
Use POJOs (Plain Old Java Objects) for complex JSON validation with
RestAssured+GsonorJackson.