Spring Boot 4.2 Testing Guide: RestTestClient, Testcontainers, and Observability
Spring Boot 4.2 changes how integration tests make HTTP calls. TestRestTemplate is deprecated in favor of RestTestClient, and the new client works with both a running server and the MockMvc infrastructure.
This guide shows how to test Spring Boot 4.2 applications using RestTestClient, Testcontainers, messaging tests, and observability assertions.
Table of Contents
- Test Dependencies
- RestTestClient Basics
- RestTestClient with MockMvc
- Testing with a Running Server
- Testcontainers for Databases
- Testing AMQP Messaging
- Testing Observability
- Testing Best Practices
- FAQs
Test Dependencies
Start with the Spring Boot test starter and add Testcontainers support for integration tests.
Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
Gradle
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
testImplementation 'org.testcontainers:postgresql'
RestTestClient Basics
RestTestClient is the modern replacement for TestRestTemplate. It provides a fluent API for sending requests and asserting responses.
Key capabilities
- Works with a running server or MockMvc.
- Supports fluent request building.
- Provides response status, header, and body assertions.
- Integrates with Spring Boot test auto-configuration.
- Uses the same
RestClientfoundation as production code.
Basic structure
restTestClient
.get()
.uri("/api/users/1")
.exchange()
.expectStatus().isOk()
.expectBody(User.class)
.consumeWith(result -> {
User user = result.getResponseBody();
});
RestTestClient with MockMvc
For controller tests, annotate the test class with @AutoConfigureRestTestClient. Spring Boot auto-configures a RestTestClient backed by MockMvc.
Controller example
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
}
Test example
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureRestTestClient;
import org.springframework.boot.resttestclient.TestRestClient;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureRestTestClient
class UserControllerTest {
@Autowired
private TestRestClient restTestClient;
@Test
void shouldReturnUser() {
restTestClient
.get()
.uri("/api/users/1")
.exchange()
.expectStatus().isOk()
.expectBody(User.class)
.consumeWith(result ->
assertThat(result.getResponseBody())
.isNotNull()
);
}
}
Testing error responses
@Test
void shouldReturnNotFoundForUnknownUser() {
restTestClient
.get()
.uri("/api/users/999")
.exchange()
.expectStatus().isNotFound();
}
Testing POST requests
@Test
void shouldCreateUser() {
UserRequest request = new UserRequest("Alice", "alice@example.com");
restTestClient
.post()
.uri("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.body(request)
.exchange()
.expectStatus().isCreated()
.expectHeader().exists("Location")
.expectBody(User.class)
.consumeWith(result ->
assertThat(result.getResponseBody().email())
.isEqualTo("alice@example.com")
);
}
Testing with a Running Server
For full integration tests, start the application on a random port and use RestTestClient to call the real server.
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureRestTestClient;
import org.springframework.boot.resttestclient.TestRestClient;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
class UserApiIntegrationTest {
@Autowired
private TestRestClient restTestClient;
@Test
void shouldReturnHealthStatus() {
restTestClient
.get()
.uri("/actuator/health")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.status").isEqualTo("UP");
}
}
When the test class uses a running server, RestTestClient resolves relative URLs against the running server automatically.
Testcontainers for Databases
Testcontainers provides real infrastructure for integration tests. It is especially useful for databases, message brokers, and external services.
PostgreSQL container example
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;
@TestConfiguration(proxyBeanMethods = false)
public class TestcontainersConfiguration {
@Bean
@ServiceConnection
PostgreSQLContainer<?> postgresContainer() {
return new PostgreSQLContainer<>(
DockerImageName.parse("postgres:17-alpine")
);
}
}
Use the container in a test
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
@SpringBootTest
@Import(TestcontainersConfiguration.class)
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
void shouldSaveAndFindUser() {
User user = new User(null, "Alice", "alice@example.com");
User saved = userRepository.save(user);
assertThat(userRepository.findById(saved.id()))
.isPresent();
}
}
Why use Testcontainers?
- Tests run against the same database engine used in production.
- No dependency on a locally installed database.
- Each test run can start with a clean database.
- Container lifecycle is managed automatically.
- Works well in CI pipelines with Docker support.
Testing AMQP Messaging
Spring Boot 4.2 adds AMQP 1.0 support. Messaging tests should verify both message production and consumption.
Testcontainers RabbitMQ example
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.testcontainers.containers.RabbitMQContainer;
import org.testcontainers.utility.DockerImageName;
@TestConfiguration(proxyBeanMethods = false)
public class RabbitMqTestConfiguration {
@Bean
@ServiceConnection
RabbitMQContainer rabbitMQContainer() {
return new RabbitMQContainer(
DockerImageName.parse("rabbitmq:4-management")
);
}
}
Producer test
@SpringBootTest
@Import(RabbitMqTestConfiguration.class)
class OrderEventPublisherTest {
@Autowired
private OrderEventPublisher publisher;
@Autowired
private AmqpTemplate amqpTemplate;
@Test
void shouldPublishOrderCreatedEvent() {
OrderCreatedEvent event = new OrderCreatedEvent(1L, "CREATED");
publisher.publishOrderCreated(event);
Object received = amqpTemplate.receiveAndConvert("orders");
assertThat(received).isNotNull();
}
}
Consumer test
@SpringBootTest
@Import(RabbitMqTestConfiguration.class)
class OrderEventConsumerTest {
@Autowired
private AmqpTemplate amqpTemplate;
@Autowired
private OrderEventConsumer consumer;
@Test
void shouldConsumeOrderCreatedEvent() {
OrderCreatedEvent event = new OrderCreatedEvent(1L, "CREATED");
amqpTemplate.convertAndSend("orders", event);
await().atMost(Duration.ofSeconds(5))
.untilAsserted(() ->
assertThat(consumer.getProcessedEvents())
.contains(event)
);
}
}
Testing Observability
Observability tests verify that metrics, traces, and health indicators behave as expected. They are useful when enabling OpenTelemetry conventions or changing monitoring configuration.
Health endpoint test
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
class HealthEndpointTest {
@Autowired
private TestRestClient restTestClient;
@Test
void healthShouldBeUp() {
restTestClient
.get()
.uri("/actuator/health")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.status").isEqualTo("UP");
}
}
Metrics endpoint test
@Test
void shouldExposeHttpServerRequestsMetric() {
restTestClient
.get()
.uri("/actuator/metrics/http.server.requests")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.name").isEqualTo("http.server.requests");
}
When OpenTelemetry semantic conventions are enabled, metric names may differ. Update assertions to match the conventions used by your application.
Testing with OpenTelemetry conventions
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "management.observations.conventions=open-telemetry"
)
@AutoConfigureRestTestClient
class OpenTelemetryMetricsTest {
@Autowired
private TestRestClient restTestClient;
@Test
void shouldExposeMetricsWithOpenTelemetryConventions() {
restTestClient
.get()
.uri("/actuator/metrics")
.exchange()
.expectStatus().isOk();
}
}
Testing Best Practices
- Use unit tests for business logic and integration tests for infrastructure.
- Prefer
RestTestClientfor new HTTP tests. - Use Testcontainers for databases and message brokers.
- Keep test data isolated and deterministic.
- Test error responses, validation failures, and security rules.
- Avoid relying on test execution order.
- Use Awaitility for asynchronous assertions.
- Run integration tests in CI with Docker available.
- Keep test execution time reasonable by reusing containers where appropriate.
Awaitility dependency
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
FAQs
What replaced TestRestTemplate in Spring Boot 4.2?
RestTestClient replaces TestRestTemplate. TestRestTemplate is deprecated for removal in Spring Boot 4.4.
How do I enable RestTestClient in a test?
Annotate the test class with @AutoConfigureRestTestClient and inject RestTestClient.
Does RestTestClient work with MockMvc?
Yes. When combined with MockMvc auto-configuration, Spring Boot provides a RestTestClient backed by the MockMvc infrastructure.
Can I use RestTestClient with a running server?
Yes. Use @SpringBootTest with a random port and @AutoConfigureRestTestClient.
Should I use Testcontainers for every test?
No. Use Testcontainers for integration tests that need real infrastructure. Unit tests should remain fast and independent.
How do I test AMQP 1.0 messaging?
Use Testcontainers to start a compatible broker, publish messages through your producer, and assert consumption with Awaitility or another asynchronous assertion mechanism.
How do I test OpenTelemetry conventions?
Set management.observations.conventions=open-telemetry in the test properties and assert the expected metric names and attributes.
Why is my Testcontainers test failing in CI?
Common causes include Docker not being available, insufficient permissions, image pull failures, or resource limits. Verify Docker access and container startup logs.
Final Thoughts
Spring Boot 4.2 provides a modern testing stack built around RestTestClient, Testcontainers, and observability assertions. Together, these tools help you test real application behavior without relying on outdated APIs.
Start by migrating HTTP tests to RestTestClient, add Testcontainers for database and messaging integration tests, and validate observability changes before production rollout.
Next in this series: Spring Boot 4.1 vs 4.2: Startup, Memory, and Build Performance Benchmarks
Comments
Post a Comment