Writing Unit Tests With Mockito And JUnit For Spring Components

Spring applications often depend on databases, HTTP clients, message brokers and payment providers. Unit tests isolate a class from those systems, so a developer can verify business rules quickly and repeatably. JUnit supplies the test structure, while Mockito creates controlled substitutes for collaborators.

This approach is especially useful for Australian applications handling customer details, NDIS-related workflows, online bookings or local payment services. A focused test suite can run on a laptop in Melbourne, in a Sydney CI pipeline or during a busy end-of-financial-year release without requiring a live environment.

Separate Business Logic From Infrastructure

A unit test should usually exercise one class, such as InvoiceService, and replace its repository or gateway with a mock. The test then checks observable behaviour: which result was returned, which dependency was called and how invalid input was handled.

Consider a service that applies a discount before saving an order:

@Service
public class OrderService {
    private final OrderRepository repository;

    public OrderService(OrderRepository repository) {
        this.repository = repository;
    }

    public Order place(Order order) {
        if (order.total().compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("Total must be positive");
        }
        return repository.save(order);
    }
}

The constructor makes the dependency explicit and allows Mockito to provide a test double without loading the complete Spring application context.

Configure JUnit And Mockito

With Spring Boot, spring-boot-starter-test normally provides JUnit Jupiter, Mockito and useful assertion libraries. The extension below initialises annotated mocks and injects them into the class under test:

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    @Mock
    private OrderRepository repository;

    @InjectMocks
    private OrderService service;
}

For a small unit test, avoid @SpringBootTest. Starting the whole context makes tests slower and can hide design problems. Use @WebMvcTest for a controller slice and @DataJpaTest for persistence-focused tests, reserving full context tests for integration coverage.

Stub Inputs And Verify Behaviour

Mockito stubbing defines what a collaborator returns:

@Test
void savesAnOrderWithPositiveTotal() {
    Order order = new Order("A100", new BigDecimal("45.00"));
    when(repository.save(order)).thenReturn(order);

    Order result = service.place(order);

    assertEquals(order, result);
    verify(repository).save(order);
}

For a rejected order, verify that persistence never occurs:

@Test
void rejectsZeroTotal() {
    Order order = new Order("A101", BigDecimal.ZERO);

    assertThrows(IllegalArgumentException.class, () -> service.place(order));

    verifyNoInteractions(repository);
}

Prefer meaningful verification over checking every internal call. Excessive Mockito expectations make refactoring painful, while assertions about returned data, exceptions and side effects keep the test aligned with business requirements.

Choose The Right Test Boundary

The best testing boundary depends on what needs confidence. A pure unit test is fast and isolated; a slice test checks Spring wiring in a limited area; an integration test confirms that real components work together.

Test style Main purpose Typical tools Speed
Unit test Business rules in one class JUnit, Mockito Very fast
Web slice Controller mappings and JSON @WebMvcTest, MockMvc Fast
Data slice Repository queries and mappings @DataJpaTest, H2 or Testcontainers Moderate
Integration test Full application collaboration @SpringBootTest Slower

For an Australian retail platform, a unit test can validate GST calculation without contacting a bank. A separate integration test can verify the payment adapter using a sandbox. This separation is valuable when production systems have rate limits, local business hours or strict test-account controls.

Test Spring MVC Components

Controller tests should focus on HTTP behaviour: status codes, validation responses, serialisation and service interaction. A @WebMvcTest(OrderController.class) test can mock OrderService and use MockMvc to send a request without starting repositories or external clients.

Check both successful and invalid payloads. Australian applications may receive addresses from Brisbane, Perth or regional areas, so validation should handle postcode formats and required fields consistently. If personal information is involved, test that error responses do not expose private data under obligations associated with the Privacy Act 1988.

Handle Exceptions And External Clients

Mockito is useful for clients that call REST APIs, email providers or payment gateways. Stub successful responses, timeouts and domain-specific failures, then assert how the Spring component translates them into application behaviour.

Use argument matchers carefully. If one matcher is used, all arguments in that invocation generally need matchers:

when(client.charge(eq("AUD"), any(BigDecimal.class)))
    .thenReturn(new ChargeResult("approved"));

For currency-sensitive systems, use BigDecimal rather than double, and test rounding rules explicitly. This matters for Australian-dollar prices, GST-inclusive invoices and payment totals governed by the expectations of the Australian Consumer Law.

Keep Tests Readable And Deterministic

Give each test a name that describes the business outcome, such as returnsConflictWhenReferenceAlreadyExists. Arrange, act and assert blocks make failures easier to diagnose. Test data builders can remove repetitive setup without concealing important values.

Avoid real clocks, random identifiers and network calls in unit tests. Inject a Clock when date logic matters, particularly around daylight-saving changes between Sydney and Brisbane. Developers working across Australian time zones should also ensure CI reports timestamps clearly and does not make tests dependent on the machine’s local zone.

A useful Java learning reference is this Java fundamentals guide, especially when test code relies on collections, exceptions, interfaces or modern language features.

Practices That Keep Tests Valuable

A reliable Mockito and JUnit suite grows alongside production behaviour rather than chasing arbitrary coverage percentages. Review failures as design feedback: difficult setup may indicate a class with too many responsibilities, while repeated mocks may suggest a missing abstraction.

Use these practices when building Spring component tests: