Spring Boot Rest Assured
- Home
- Spring Boot Rest Assured
Integrating Rest Assured with Spring Boot is a common approach for writing integration tests for REST APIs. It allows you to test real HTTP requests against your Spring application using a fluent and expressive Java DSL.
Use Case
You can use Rest Assured to:
Test controllers with full Spring context
Validate JSON/XML responses
Simulate real HTTP requests (with port binding or
MockMvc
)
1. Add Dependencies (pom.xml
)
<dependencies>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Rest Assured for Java -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
2. Sample Controller (Spring Boot)
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public ResponseEntity<Map<String, Object>> getUser(@PathVariable int id) {
Map<String, Object> user = Map.of(
"id", id,
"name", "John Doe",
"email", "john.doe@example.com"
);
return ResponseEntity.ok(user);
}
}
3. Integration Test with Rest Assured
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
@LocalServerPort
private int port;
@BeforeEach
public void setUp() {
RestAssured.port = port;
}
@Test
public void shouldReturnUser() {
given()
.contentType(ContentType.JSON)
.when()
.get("/api/users/1")
.then()
.statusCode(200)
.body("id", equalTo(1))
.body("name", equalTo("John Doe"))
.body("email", containsString("@example.com"));
}
}
Notes
@SpringBootTest(webEnvironment = RANDOM_PORT)
runs the app on a real HTTP port.@LocalServerPort
injects that port into the test.You can also use
MockMvcRestAssured
for tests without full server startup if preferred.
Alternate: Rest Assured with MockMvc
To avoid running a full HTTP server, you can use:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
And test like:
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
RestAssuredMockMvc.mockMvc(mockMvc);