Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – LambdaTest – NPI (cat= Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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:

  1. Bind to an already initialised MockMvc instance to use as the server: bindTo(MockMvc mockMvc)
  2. Bind to a live server: bindToServer(ClientHttpRequestFactory requestFactory)
  3. Bind to a WebApplicationContext: bindToApplicationContext(WebApplicationContext context)
  4. Bind to (multiple) RouterFunction(s): bindToRouterFunction(RouterFunction<?>… routerFunctions)
  5. 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:

  1. Setting up a base url, like a prefix /public
  2. Setting default headers, like content type
  3. 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.

Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments