Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:
A Guide to RestTestClient
Last updated: November 28, 2025
1. Introduction
Spring’s testing ecosystem has evolved from mock-based simulations to full integration with embedded servers. The latest addition, RestTestClient in Spring Framework 7.0, bridges the gap by offering a concise, builder-style interface for HTTP interactions without the ceremony of traditional clients. This makes it a lightweight alternative to MockMvc or WebTestClient – ideal for integration tests that need speed, readability, and flexibility.
In this tutorial, we’ll set up RestTestClient in a Spring Boot project, explore practical examples covering basic requests, error handling, assertions, and more, and highlight best practices to ensure our tests are robust and maintainable.
2. Setting up RestTestClient
To use RestTestClient, we need a Spring Boot project with the appropriate testing dependencies.
Let’s start by including the Spring Boot Test starter in our pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
We also must ensure we’re using Spring Framework 7.0 or later, as RestTestClient is a newer addition.
Next, let’s configure a test class with the @SpringBootTest annotation to load the application context:
@SpringBootTest
class RestTestClientUnitTest {
private RestTestClient restTestClient;
@BeforeEach
void beforeEach() {
// TODO: initialize restTestClient
}
}
This setup allows us to instantiate the RestTestClient any way we like, in the beforeEach() method.
2.1. Binding
Before writing tests, we must decide how to create our RestTestClient. One of its strengths is the variety of binding options:
- Bind to an already initialised MockMvc instance to use as the server: bindTo(MockMvc mockMvc)
- Bind to a live server: bindToServer(ClientHttpRequestFactory requestFactory)
- Bind to a WebApplicationContext: bindToApplicationContext(WebApplicationContext context)
- Bind to (multiple) RouterFunction(s): bindToRouterFunction(RouterFunction<?>… routerFunctions)
- Bind to (multiple) Controllers: bindToController(Object… controllers)
These options bring a high level of flexibility, which makes it an optimal choice testing any Spring Boot project.
2.2. Configuration
The final step before testing is client configuration. We can fine-tune RestTestClient via its builder:
restTestClientBuilder
.baseUrl("/public") // 1
.defaultHeader("ContentType", "application/json") // 2
.defaultCookie("JSESSIONID", "abc123def456ghi789") // 3
.build();
The three options in the example are:
- Setting up a base url, like a prefix /public
- Setting default headers, like content type
- Setting a default cookie, like a session ID
With setup complete, we’re ready for our first test.
3. Practical Examples
Let’s explore several scenarios to highlight RestTestClient’s flexibility, including different types of use cases and complex assertions.
The following tests will be bound to and run against our controller:
@RestController("my")
class MyController {
@GetMapping("/persons/{id}")
public ResponseEntity<Person> getPersonById(@PathVariable Long id) {
return id == 1
? ResponseEntity.ok(new Person(1L, "John Doe"))
: ResponseEntity.noContent().build();
}
}
The getPersonById() method is returning the entity Person:
record Person(Long id, String name) { }
3.1. Happy Path
Our first test will cover a happy path, by calling a GET request to fetch a person by its id:
@Test
void givenValidPath_whenCalled_thenReturnOk() {
restTestClient.get() // 1
.uri("/persons/1") // 2
.accept(MediaType.APPLICATION_JSON) // 3
.exchange() // 4
.expectStatus() // 5
.isOk() // 6
.expectBody(Person.class) // 7
.isEqualTo(new Person(1L, "John Doe")); // 8
}
We’re using the API of RestTestClient to (1) initialise an appropriate request to (2) a certain path, with (3) appropriate accept header. We then (4) execute it, and (5) check for the expected status – OK (6) in our case. Lastly, we (7) convert the body to the return type Person and (8) assert it towards the expected instance.
This looks pretty straight forward, but how would we check for an unsuccessful request?
3.2. Simple Error Cases
Our second test covers a client error (wrong HTTP method):
@Test
void givenWrongMethod_whenCalled_thenReturnClientError() {
restTestClient.post() // <== wrong method
.uri("/persons/1")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.is4xxClientError();
}
And this is how we’d check for NO_CONTENT response (invalid ID):
@Test
void givenWrongId_whenCalled_thenReturnNoContent() {
restTestClient.get()
.uri("/persons/0") // <== wrong id
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isNoContent();
}
3.3. Json Assertions
RestTestClient integrates seamlessly with JSON Path for detailed body assertions:
@Test
void givenValidId_whenGetPerson_thenReturnsCorrectFields() {
restTestClient.get()
.uri("/persons/1")
.exchange()
.expectStatus()
.isOk()
.expectBody()
.jsonPath("$.id").isEqualTo(1)
.jsonPath("$.name").isEqualTo("John Doe");
}
This avoids full object deserialisation while verifying structure and values precisely.
3.4. Custom Assertions
If we prefer custom assertions for more complex scenarios, we can use the consumeWith() method:
@Test
void givenValidRequest_whenGetPerson_thenPassesAllAssertions() {
restTestClient.get()
.uri("/persons/1")
.exchange()
.expectStatus()
.isOk()
.expectBody(Person.class)
.consumeWith(result -> {
assertThat(result.getStatus().value()).isEqualTo(200);
assertThat(result.getResponseBody().name()).isNotNull().isEqualTo("John Doe");
});
}
In the Consumer<EntityExchangeResult<B>> that we provide, we can use any assertions we want, like the AssertJ library.
3.5. Multiple Controllers
The last scenario we’ll be looking at using multiple controllers at once.
RestTestClient makes it possible to bind more than one controller:
restTestClient = RestTestClient.bindToController(myController, anotherController)
.build();
Now we can write a test, asserting the endpoint of the second controller, in the same test class:
@Test
void givenValidQueryToSecondController_whenGetPenguinMono_thenReturnsEmpty() {
restTestClient.get()
.uri("/pink/penguin")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(Penguin.class)
.value(it -> assertThat(it).isNull());
}
This approach is useful for testing composite APIs or modular services, ensuring interactions between controllers work as expected without a full server spin-up.
4. Best Practices and Pitfalls
Since we’ve covered the basics, let’s go for a deep dive into extended possibilities and pitfalls of the new RestTestClient.
4.1. Choosing the Wrong Binding Setup
One of the first things to get right when using RestTestClient is which binding mode to use. The API supports a wide range of bindings, as previously mentioned. It’s easy to pick the wrong one.
A common pitfall is using the “mock” binding (controller or context) when we really need full server behaviour. For example, if we bind to a controller, we may not exercise the full HTTP stack (servlet filters, Spring Security, message converters registered globally)!
Wrong bindings can lead to false-negatives in tests (things pass but will fail in production). We should make sure, the binding method and the arguments provided are valid for the expected use case.
4.2. Thread Safety and Context
RestTestClient instances are immutable once built, making them thread-safe and suitable for parallel test execution. This immutability ensures no shared mutable state, allowing safe reuse across tests without race conditions, which is ideal for speeding up large test suites.
The RestTestClient.Builder, however, is mutable and not thread-safe. Sharing a single builder instance across tests or threads can lead to unpredictable configurations, like overwritten headers.
We should either create a fresh builder per test, or use only the built immutable instances (recommended).
4.3. Unnoticed Differences in Behaviour
A tricky risk with RestTestClient is its subtle behavioural differences compared to other test clients like WebTestClient. For example, there is an open issue where RestTestClient returns null for returnResult().getResponseBody() when the controller returns no body, whereas WebTestClient returns an empty byte[].
This means that if we write our assertions expecting an empty body and we switch contexts (client vs real server) we might face NPEs or misleading results.
Best practice: we should explicitly assert expectBody().isEmpty() when no body is expected rather than relying on returnResult() and then check for null vs array.
5. Conclusion
In this article, we explored RestTestClient, a modern, fluent addition to Spring Framework 7.0 that simplifies REST integration testing in Spring Boot.
From flexible binding and configuration to expressive assertions on JSON, headers and cookies, it strikes a balance between readability and power – making it an excellent choice over heavier alternatives.
As always, the code is available over on GitHub.















