Skip to main content

Introduction to JUnit 5 Testing in Spring Boot

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.

Pick a language, then press Listen.

Understanding JUnit 5 Architecture

Spring Boot JUnit 5 Testing Workflow Spring Boot JUnit 5 Testing Workflow 1 Add Dependencies Include spring-boot-starter-test in your pom.xml file 2 Configure JUnit 5 Utilize JUnit Jupiter annotations like @Test and @BeforeEach 3 Isolate Dependencies Use Mockito to mock external services like PaymentClient 4 Write Unit Tests Test business logic such as OrderService processOrder methods
Figure: Spring Boot JUnit 5 Testing Workflow

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 @BeforeEach or @Sql scripts 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 the jupiter packages.

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.
  • @SpringBootTest and TestRestTemplate enable 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

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...