Effective testing separates production-ready software from fragile prototypes. In modern enterprise Java development, testing a Spring Boot application requires mastering JUnit 5, the standard testing framework, alongside Mockito for dependency isolation. This guide covers writing clean, maintainable unit and integration tests using Spring Boot 3.x and JUnit 5, applying production best practices from the start.
Understanding JUnit 5 Architecture
JUnit 5 represents a complete redesign of the testing framework, split into three distinct sub-projects: JUnit Platform, JUnit Jupiter, and JUnit Vintage. JUnit Jupiter introduces the new programming and extension model, utilizing annotations such as @Test, @BeforeEach, and @ParameterizedTest. Unlike JUnit 4, JUnit 5 uses Java 8+ features natively, supporting lambdas, dynamic tests, and parallel execution out of the box.
When working with modern domain models built using Java 17 Records and Pattern Matching with Examples, JUnit 5 assertions align cleanly with immutable data structures, eliminating boilerplate getter calls in test assertions.
Setting Up Dependencies
Spring Boot simplifies testing configuration by bundling JUnit 5, Mockito, AssertJ, and Hamcrest into the spring-boot-starter-test dependency. Ensure your pom.xml includes the following configuration:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
By default, Spring Boot manages the versions for JUnit Jupiter (5.10+) and Mockito (5.x), ensuring compatibility with modern JVM runtimes.
Writing Unit Tests with JUnit 5 and Mockito
Unit tests isolate a single class, replacing its external dependencies with mocks. Consider an OrderService that relies on an OrderRepository and a PaymentClient.
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final PaymentClient paymentClient;
public OrderService(OrderRepository orderRepository, PaymentClient paymentClient) {
this.orderRepository = orderRepository;
this.paymentClient = paymentClient;
}
public Order processOrder(Order order) {
if (order == null || order.getAmount() <= 0) {
throw new IllegalArgumentException("Invalid order amount");
}
boolean paymentSuccess = paymentClient.charge(order.getId(), order.getAmount());
if (!paymentSuccess) {
throw new PaymentFailedException("Payment processing failed");
}
order.setStatus("COMPLETED");
return orderRepository.save(order);
}
}
To test this service without hitting a real database or payment gateway, use Mockito annotations combined with JUnit 5:
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private OrderRepository orderRepository;
@Mock
private PaymentClient paymentClient;
@InjectMocks
private OrderService orderService;
@Test
@DisplayName("Should process order successfully when payment succeeds")
void testProcessOrderSuccess() {
// Arrange
Order order = new Order(1L, 150.0, "PENDING");
when(paymentClient.charge(1L, 150.0)).thenReturn(true);
when(orderRepository.save(any(Order.class))).thenReturn(order);
// Act
Order result = orderService.processOrder(order);
// Assert
assertNotNull(result);
assertEquals("COMPLETED", result.getStatus());
verify(paymentClient, times(1)).charge(1L, 150.0);
verify(orderRepository, times(1)).save(order);
}
}
Writing Integration Tests with Spring Boot
While unit tests isolate components, integration tests verify that multiple layers—controllers, services, and repositories—interact correctly. The @SpringBootTest annotation loads the complete Spring application context.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
class OrderIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private OrderRepository orderRepository;
@BeforeEach
void setUp() {
orderRepository.deleteAll();
}
@Test
void shouldCreateAndRetrieveOrder() {
OrderRequest request = new OrderRequest(250.0, "USD");
ResponseEntity<OrderResponse> response = restTemplate.postForEntity(
"/api/orders", request, OrderResponse.class
);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals("PENDING", response.getBody().status());
}
}
When containerized architectures require database validation, pairing these tests with Testcontainers ensures your integration suite executes against a real database instance rather than an in-memory substitute like H2, preventing dialect mismatches later.
Unit Tests vs. Integration Tests Comparison
| Feature | Unit Tests | Integration Tests |
|---|---|---|
| Speed | Extremely fast (milliseconds) | Slower (seconds to minutes) |
| Spring Context | Not loaded (pure JVM execution) | Fully or partially loaded |
| Dependencies | Mocked using Mockito | Real or containerized (Testcontainers) |
| Primary Goal | Verify business logic of a single class | Verify wiring and external component interactions |
Real-World Edge Cases to Handle
Production code rarely follows the happy path exclusively. Your test suite must account for complex edge cases:
1. Handling Transient Failures and Retries
External network clients often fail temporarily. If your application uses Spring Retry, write tests verifying that service calls attempt recovery the expected number of times before throwing an exception:
@Test
void shouldRetryOnTransientNetworkFailure() {
when(paymentClient.charge(anyLong(), anyDouble()))
.thenThrow(new NetworkTimeoutException("Timeout"))
.thenReturn(true);
Order order = new Order(1L, 100.0, "PENDING");
Order result = orderService.processOrder(order);
assertEquals("COMPLETED", result.getStatus());
verify(paymentClient, times(2)).charge(anyLong(), anyDouble());
}
2. Concurrency and Race Conditions
When multiple threads modify shared states or database records simultaneously, optimistic locking exceptions can occur. Test repository constraints using multi-threaded execution models or CountdownLatches in JUnit 5 to ensure your service layer handles ObjectOptimisticLockingFailureException gracefully.
3. Null and Boundary Parameter Injection
Avoid relying solely on valid inputs. Use JUnit 5 parametrized tests to feed invalid parameters, empty strings, and boundary limits directly into your methods:
@ParameterizedTest
@ValueSource(doubles = {0.0, -10.0, -0.01})
void shouldThrowExceptionForInvalidAmounts(double invalidAmount) {
Order order = new Order(1L, invalidAmount, "PENDING");
assertThrows(IllegalArgumentException.class, () -> orderService.processOrder(order));
}
Troubleshooting Common Testing Pitfalls
Developers frequently encounter specific friction points when configuring JUnit 5 and Spring Boot:
- Application Context Pollution: If one test modifies static state or a shared database without cleanup, subsequent tests may fail unpredictably. Always use
@BeforeEachor@Sqlscripts to reset state. - MockitoStubbingException: This occurs when strict stubbing is enabled and unnecessary stubs are declared. Keep mock configurations relevant to the specific test scenario.
- Legacy Test Configurations: Mixing JUnit 4 annotations (
org.junit.Test) with JUnit 5 (org.junit.jupiter.api.Test) causes tests to be silently ignored by the build runner. Ensure all imports reference thejupiterpackages.
In environments where legacy infrastructure requires specific database drivers—such as older Oracle setups requiring JNDI configuration for Tomcat 9 with Oracle—ensure your test profile mocks the JNDI context properly using Spring's SimpleNamingContextBuilder to prevent lookup failures during test initialization.
Summary
- JUnit 5 offers a modular, high-performance foundation for Java testing, leveraging annotations like
@Test,@BeforeEach, and@ParameterizedTest. - Mockito isolates components by mocking external dependencies, ensuring unit tests run fast and deterministically.
@SpringBootTestandTestRestTemplateenable comprehensive integration testing across the entire application stack.- Always account for real-world edge cases including transient network failures, retry logic, concurrency limits, and boundary inputs.
- Maintain clean separation between fast, isolated unit tests and slower, comprehensive integration suites.
Comments
Post a Comment