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.

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

1. Overview

Let’s dive into the world of Spring Boot testing! In this tutorial, we’ll take a deep dive into the @SpringBootTest and @WebMvcTest annotations. We’ll explore when and why to use each one and how they work together to test our Spring Boot applications. Plus, we’ll uncover the inner workings of MockMvc and how it interacts with both annotations in integration tests.

2. What Are @WebMvcTest and @SpringBootTest

The @WebMvcTest annotation is used to create MVC (or more specifically controller) related tests. It can also be configured to test for a specific controller. It mainly loads and makes testing of the web layer easy.

The @SpringBootTest annotation is used to create a test environment by loading a full application context (like classes annotated with @Component and @Service, DB connections, etc). It looks for the main class (which has the @SpringBootApplication annotation) and uses it to start the application context.

Both of these annotations were introduced in Spring Boot 1.4.

3. Project Setup

For this tutorial, we’ll create two classes namely SortingController and SortingService. SortingController receives a request with a list of integers and uses a helper class SortingService which has the business logic to sort the list.

We’ll be using constructor injection to get SortingService dependency as shown below:

@RestController public class SortingController { private final SortingService sortingService; public SortingController(SortingService sortingService){ this.sortingService=sortingService; }

// ... }

Let’s declare a GET method to check our server running and this will also help us explore the working of annotations during testing:

@GetMapping public ResponseEntity<String> helloWorld(){ return ResponseEntity.ok("Hello, World!"); }

Next, we’ll also have a post method that takes an array as a JSON body and returns a sorted array in response. Testing this type of method will help us to understand the use of MockMvc:

@PostMapping public ResponseEntity<List<Integer>> sort(@RequestBody List<Integer> arr){ return ResponseEntity.ok(sortingService.sortArray(arr)); }

4. Comparing @SpringBootTest and @WebMvcTest 

The @WebMvcTest annotation is located in the org.springframework.boot.test.autoconfigure.web.servlet package, whereas @SpringBootTest is located in org.springframework.boot.test.context. Spring Boot, by default, adds the necessary dependencies to our project assuming that we plan to test our application. At the class level, we can use either one of them at a time.

4.1. Using MockMvc

In a @SpringBootTest context, MockMvc will automatically call the actual service implementation from the controller. The service layer beans will be available in the application context. To use MockMvc within our tests, we’ll need to add the @AutoConfigureMockMvc annotation. This annotation creates an instance of MockMvc, injects it into the mockMvc variable, and makes it ready for testing without requiring manual configuration:

@AutoConfigureMockMvc @SpringBootTest class SortingControllerIntegrationTest { @Autowired private MockMvc mockMvc; }

In @WebMvcTest, MockMvc will be accompanied by @MockBean of the service layer to mock service layer responses without calling the real service. Also, service layer beans are not included in the application context. It provides @AutoConfigureMockMvc by default:

@WebMvcTest class SortingControllerUnitTest { @Autowired private MockMvc mockMvc; @MockBean private SortingService sortingService; }

Note: When using @SpringBootTest with webEnvironment=RANDOM_PORT, be cautious about using MockMvc because MockMvc tries to make sure that whatever is needed for handling web requests is in place and no servlet container (handles incoming HTTP requests and generates responses) is started while webEnvironment=RANDOM_PORT tries to bring up the servlet container. They both contradict each other if used in conjunction.

4.2. What Is Autoconfigured?

In @WebMvcTest, Spring Boot automatically configures the MockMvc instance, DispatcherServlet, HandlerMapping, HandlerAdapter, and ViewResolvers. It also scans for @Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, Filter, WebMvcConfigurer, and HandlerMethodArgumentResolver components.  In general, it autoconfigures web layer-related components.

@SpringBootTest loads everything that @SpringBootApplication (SpringBootConfiguration+ EnableAutoConfiguration + ComponentScan) does i.e. a fully-fledged application context. It even loads the application.properties file and the profile-related info. It also enables beans to inject like using @Autowired.

4.3. Lightweight or Heavyweight

We can say that @SpringBootTest is heavyweight as it is mostly configured for integration testing by default unless we want to use any mocks. It also has all the beans in the application context. This also is the reason for it being slower as compared to others.

On the other hand, @WebMvcTest is more isolated and only concerned about the MVC layer. It is ideal for unit testing. We can be specific to one or more controllers also. It has a limited number of beans in the application context. Also, while running we can observe the same time difference (i.e. less running time with @WebMvcTest) for test cases to complete.

4.4. Web Environment During Testing

When we start a real application, we usually hit “http://localhost:8080” to access our application. To imitate the same scenario during testing we use webEnvironment. And using this we define a port for our test cases (similar to 8080 in URL). @SpringBootTest can step in both the simulated webEnvironment (WebEnvironment.MOCK) or real webEnvironment (WebEnvironment.RANDOM_PORT) while @WebMvcTest provides only the simulated test environment.

Following is the code example for it @SpringBootTest with WebEnvironment:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class SortingControllerWithWebEnvironmentIntegrationTest { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Autowired private ObjectMapper objectMapper; }

Now let’s use them in action for writing test cases. Following is the test case for the GET method: 

@Test void whenHelloWorldMethodIsCalled_thenReturnSuccessString() { ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:" + port + "/", String.class); Assertions.assertEquals(HttpStatus.OK, response.getStatusCode()); Assertions.assertEquals("Hello, World!", response.getBody()); }

Following is the test case to check the correctness of the POST method:

@Test void whenSortMethodIsCalled_thenReturnSortedArray() throws Exception { List<Integer> input = Arrays.asList(5, 3, 8, 1, 9, 2); List<Integer> sorted = Arrays.asList(1, 2, 3, 5, 8, 9); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ResponseEntity<List> response = restTemplate.postForEntity("http://localhost:" + port + "/", new HttpEntity<>(objectMapper.writeValueAsString(input), headers), List.class); Assertions.assertEquals(HttpStatus.OK, response.getStatusCode()); Assertions.assertEquals(sorted, response.getBody()); }

4.5. Dependencies

@WebMvcTest does not detect dependencies needed for the controller automatically, so we’ve to Mock them. While @SpringBootTest does it automatically.

Here we can see we’ve used @MockBean because we’re calling a service from inside a controller:

@WebMvcTest class SortingControllerUnitTest { @Autowired private MockMvc mockMvc; @MockBean private SortingService sortingService; }

Now let’s see a test example of using MockMvc with a mocked bean:

@Test void whenSortMethodIsCalled_thenReturnSortedArray() throws Exception { List<Integer> input = Arrays.asList(5, 3, 8, 1, 9, 2); List<Integer> sorted = Arrays.asList(1, 2, 3, 5, 8, 9); when(sortingService.sortArray(input)).thenReturn(sorted); mockMvc.perform(post("/").contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(input))) .andExpect(status().isOk()) .andExpect(content().json(objectMapper.writeValueAsString(sorted))); } 

Here we’ve used when().thenReturn() to mock the sortArray() function in our service class. Not doing that will cause a NullPointerException.

4.6. Customization

@SpringBootTest is mostly not a good choice for customization but @WebMvcTest can be customized to work with only limited controller classes. In the following example, I have mentioned the SortingController class specifically. So only one controller with its dependencies is registered with the application:

@WebMvcTest(SortingController.class) class SortingControllerUnitTest { @Autowired private MockMvc mockMvc; @MockBean private SortingService sortingService; @Autowired private ObjectMapper objectMapper; }

5. Conclusion

@SpringBootTest and @WebMvcTest, each serve distinct purposes. @WebMvcTest is designed for MVC-related tests, focusing on the web layer and providing easy testing for specific controllers. On the other hand, @SpringBootTest creates a test environment by loading a full application context, including @Components, DB connections, and @Service, making it suitable for integration and system testing, similar to the production environment.

When it comes to using MockMvc, @SpringBootTest internally calls actual service implementation from the controller, while @WebMvcTest is accompanied by @MockBean for mocking service layer responses without calling the real service.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
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)