A practical Guide to Testing Spring Boot Microservices
Learn how to test Spring Boot microservices with JUnit, Mockito, MockMvc, Testcontainers, contract testing, and JaCoCo.

Audio controls for A practical Guide to Testing Spring Boot Microservices
Listen to this article
Testing is essential for building reliable, maintainable Spring Boot microservices. A good testing strategy verifies business logic, validates application behaviour, checks database interactions, and catches compatibility issues between services.
In this guide, we'll explore practical testing techniques using a typical Spring Boot microservices architecture consisting of:
identity-service— manages authentication and user profiles.task-service— manages tasks, categories, and deadlines.
We'll use JUnit Jupiter, Mockito, Spring Boot testing support, Testcontainers, and JaCoCo to demonstrate how to test different application boundaries.
The examples target Spring Boot 4.x. Use dependencies managed by your Spring Boot version's dependency management rather than copying arbitrary library versions into your project.
1. Understanding the Testing Strategy
Microservices benefit from a combination of testing techniques. No single type of test can provide sufficient confidence on its own.
Unit tests
Unit tests verify individual classes or business rules in isolation. Dependencies such as repositories and external service clients are replaced with mocks or other test doubles.
Use them for: business logic, calculations, validation rules, and exception handling.
Slice tests
Slice tests load only the relevant part of the Spring application context.
Examples include:
@WebMvcTestfor Spring MVC controllers.@DataJpaTestfor JPA repositories and persistence behaviour.
Use them for: HTTP request handling, serialization, validation, and database mapping.
Integration tests
Integration tests verify that multiple application components work together, often with a real database or other infrastructure.
Use them for: persistence, security configuration, application wiring, and communication with dependencies.
End-to-end tests
End-to-end tests exercise complete workflows across multiple components or services.
Use them for: critical business journeys where the interaction between services matters.
A practical strategy is to write many fast unit tests, a focused set of integration tests, and a smaller number of end-to-end tests.
2. Setting Up Testing Dependencies
Spring Boot's dependency management helps keep compatible library versions aligned.
For a Maven project, declare the relevant test dependencies in the modules that need them. With Spring Boot 4, use the appropriate modular test starters for the functionality being tested.
For example, a module using MVC, security, JPA, and PostgreSQL integration tests may need dependencies such as:
<dependencies>
<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-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>These are illustrative dependencies for a module that uses all the listed capabilities. Check the Spring Boot 4.x documentation for the appropriate starter and module dependencies for your specific application.
In a multi-module Maven project, use the parent POM's dependencyManagement section or Spring Boot's parent POM to manage versions centrally. Remember that dependencyManagement does not add dependencies to child modules automatically.
Useful Maven commands
# Run tests in the current module
mvn test
# Run tests in one service module
mvn -pl task-service test
# Run a service module and its required reactor dependencies
mvn -pl task-service -am verify
# Run verification and generate configured coverage reports
mvn clean verifyThe exact JaCoCo report location depends on how the plugin is configured, especially in a multi-module project.
3. Unit Testing with JUnit and Mockito
Unit tests should be fast, deterministic, and focused on observable behaviour.
Consider a service that retrieves a user through a repository and converts the entity into a DTO.
@ExtendWith(MockitoExtension.class)
class UserServiceImplTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserServiceImpl userService;
@Test
void getUserById_shouldReturnUser() {
User user = new User(
1L,
"test@example.com",
"encoded-password"
);
when(userRepository.findById(1L))
.thenReturn(Optional.of(user));
UserDto result = userService.getUserById(1L);
assertEquals("test@example.com", result.getEmail());
verify(userRepository).findById(1L);
}
@Test
void getUserById_shouldThrowWhenUserDoesNotExist() {
when(userRepository.findById(99L))
.thenReturn(Optional.empty());
assertThrows(
UserNotFoundException.class,
() -> userService.getUserById(99L)
);
}
}The exception in the second test is illustrative: adapt it to the exception contract implemented by your service.
Unit testing best practices
- Follow the Given–When–Then pattern.
- Test success paths, failure paths, and important edge cases.
- Mock dependencies rather than starting the Spring application context unnecessarily.
- Assert meaningful outcomes rather than implementation details.
- Verify interactions when they are part of the behaviour being tested.
- Use safe synthetic test data and never use real credentials.
A unit test should explain what the code is expected to do, not merely confirm that a method was called.
4. Testing REST Controllers with MockMvc
Controllers handle HTTP requests, input validation, serialization, and response status codes. Spring MVC slice tests allow you to test this behaviour without starting the complete application.
For a focused controller test, use @WebMvcTest and mock the service dependency.
@WebMvcTest(TaskController.class)
class TaskControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@MockitoBean
private TaskService taskService;
@Test
void createTask_shouldReturn201() throws Exception {
TaskRequest request = new TaskRequest(
"Task A",
"Description",
LocalDateTime.now().plusDays(1)
);
TaskDto response = new TaskDto(
1L,
"Task A",
"Description"
);
when(taskService.createTask(any(TaskRequest.class)))
.thenReturn(response);
mockMvc.perform(post("/api/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.title").value("Task A"));
}
}The DTO and request constructors above are illustrative; adjust them to match your application's actual model.
Spring Boot 4 supports @MockitoBean for replacing a bean in the test application context with a Mockito mock. Older applications may still use @MockBean.
MockMvc versus a running server
These two approaches serve different purposes.
MockMvc: Use it to test Spring MVC request processing without making a real network request. It is generally a good choice for controller and security tests.
Running-server integration tests: Use @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) with an HTTP client when you need to exercise the embedded server over a real HTTP connection.
Do not combine RANDOM_PORT with MockMvc as though the latter sends requests to that port. Choose the testing approach that matches the boundary you want to verify.
5. Testing Persistence with PostgreSQL and Testcontainers
Repository tests should validate queries, mappings, constraints, and database behaviour.
An in-memory database can be useful for fast tests, but it may behave differently from PostgreSQL in areas such as SQL syntax, types, constraints, and database-specific features.
Testcontainers allows tests to use a real PostgreSQL instance managed by Docker.
Configure a PostgreSQL container
Spring Boot 4 supports service connections that automatically provide connection details to compatible auto-configuration.
@Testcontainers
@DataJpaTest
@ImportAutoConfiguration(
classes = {
org.springframework.boot.testcontainers.service.connection
.ServiceConnectionAutoConfiguration.class
}
)
class TaskRepositoryTest {
@Container
@ServiceConnection
static final PostgreSQLContainer postgres =
new PostgreSQLContainer("postgres:16");
@Autowired
private TaskRepository taskRepository;
@Test
void save_shouldPersistTask() {
Task task = new Task();
task.setTitle("Test task");
Task saved = taskRepository.saveAndFlush(task);
assertNotNull(saved.getId());
assertEquals("Test task", saved.getTitle());
}
}Use the PostgreSQL container class and service-connection imports supplied by the Testcontainers and Spring Boot versions managed by your project. The example assumes a compatible PostgreSQL container implementation and a repository/entity model with the shown fields.
The test also assumes your application schema can be created through the test configuration, entity mappings, or database migrations. Configure Flyway or Liquibase appropriately if your production application uses migrations.
Why Testcontainers matters
- Tests run against the actual database engine.
- Database-specific behaviour is exercised more realistically.
- Container configuration can be reproduced in developer environments and CI.
- Spring Boot can configure supported service connections without manually copying datasource URLs and credentials into properties.
Test isolation
Database isolation still requires deliberate design.
@DataJpaTest normally wraps each test in a transaction and rolls it back. This is useful for repository tests, but it does not automatically clean up every external side effect.
For tests using a running HTTP server, requests are processed on separate server threads and may use transactions independent of the test thread. In those cases, use explicit database cleanup, isolated test data, or a suitable reset strategy.
6. Testing Microservice Communication
Microservices often call other services through HTTP clients such as Spring Cloud OpenFeign.
For unit and focused integration tests, mocking a client allows you to exercise the calling service without depending on the availability of the remote service.
@SpringBootTest
class TaskServiceIntegrationTest {
@MockitoBean
private IdentityServiceClient identityServiceClient;
@Autowired
private TaskService taskService;
@Test
void getTasks_shouldHandleIdentityServiceResponse() {
when(identityServiceClient.getUserById(1L))
.thenReturn(
new UserDto(1L, "test@example.com", "Test User")
);
// Exercise the task service and assert its actual result.
// Adapt the invocation to the application's service API.
}
}This example replaces the identity client in the Spring application context. It does not start or contact the real identity service.
What should be tested?
- Successful responses from the remote service.
- HTTP error responses and exception mapping.
- Connection failures and timeout behaviour.
- Authentication and authorization between services.
- Request and response serialization.
- Retry behaviour, where configured.
Mocks are valuable, but they cannot prove that two independently deployed services agree on their API.
For stronger compatibility guarantees, consider:
- WireMock to simulate HTTP responses and test client behaviour.
- Spring Cloud Contract or Pact to validate service contracts.
- A smaller number of integration tests against real dependent services when the additional confidence justifies the cost.
7. Testing Spring Security
Security tests should verify both successful access and denied access.
For example, @WithMockUser can establish an authenticated test principal for a secured endpoint.
@Test
@WithMockUser(username = "admin", roles = "ADMIN")
void deleteTask_withAdminRole_shouldSucceed() throws Exception {
mockMvc.perform(delete("/api/tasks/1"))
.andExpect(status().isNoContent());
}This example assumes the controller is configured to authorize the request and that the service operation succeeds. The actual status code should match your API contract.
Also test:
- Requests without authentication.
- Authenticated users with insufficient permissions.
- Access to another user's resources.
- Invalid request data and rejected operations.
- JWT validation and authority mapping when the application acts as an OAuth 2.0 resource server.
@WithMockUser does not validate a real JWT signature or reproduce your production identity provider. Use the relevant Spring Security test support for JWT-specific scenarios.
8. Measuring Coverage with JaCoCo
JaCoCo generates code coverage reports that help identify untested parts of the application.
A basic Maven plugin configuration is:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>verify</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>Define jacoco.version centrally using a version compatible with your Java toolchain, and ensure the plugin is configured in the appropriate parent or module POM.
Run:
mvn clean verifyFor a conventional single-module project, the HTML report is usually generated under:
target/site/jacoco/index.htmlFor a multi-module project, configure aggregate reporting if you want a consolidated view across services.
Coverage is not test quality
JaCoCo can report line and branch coverage, but neither metric proves that your assertions are meaningful.
A test suite with high coverage may still fail to detect incorrect business rules or broken security boundaries.
Prioritise critical behaviour and meaningful assertions. Add coverage thresholds where they help prevent regressions, rather than pursuing an arbitrary percentage for its own sake.
9. Running Tests in CI/CD
A reliable pipeline should provide fast feedback while exercising important integration boundaries.
A practical sequence is:
- Compile the application and run unit tests.
- Run focused MVC and persistence tests.
- Run Testcontainers-based integration tests in an environment with Docker support.
- Generate and, where appropriate, enforce JaCoCo coverage reports.
- Run a focused set of end-to-end or contract verification tests.
- Publish test and coverage reports for review.
Keep tests deterministic and independent. Avoid shared mutable test data, dependencies on external production systems, and tests that rely on execution order.
If integration tests are expensive, separate them into an appropriate Maven profile or CI stage, while ensuring they still run regularly and before important releases.
10. Key Takeaways
Testing Spring Boot microservices is about building confidence at the right boundaries.
- Unit tests provide fast feedback on business logic.
- Slice tests validate individual application layers.
- Integration tests verify that components and infrastructure work together.
- Testcontainers makes realistic database testing reproducible.
- Contract tests help detect incompatibilities between services.
- Security tests verify authentication and authorization behaviour.
- JaCoCo helps identify gaps, but coverage alone is not a measure of quality.
- CI/CD makes the testing strategy repeatable and part of the delivery process.
Start with isolated unit tests, add realistic integration tests for important dependencies, and use end-to-end tests selectively for critical workflows.
A well-designed test suite is not simply a collection of passing tests. It is an engineering tool that helps you change, deploy, and evolve microservices with confidence.
Further Reading
Did you find this article useful?