Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 41 ยท Testing and Quality

Testing with JUnit and Mockito in a Maven project

Add JUnit and Mockito to a Maven project with the right scopes, write unit tests with mocks, stubs, verification and captors, and run them with Surefire.

Running Tests with Surefire showed how Maven finds and runs JUnit tests. Real classes, though, rarely stand alone. An OrderService calls a PaymentGateway that charges a card, a UserRepository that talks to a database and an EmailSender that sends mail. In a unit test you do not want real money, a real database or real email. You replace those collaborators with test doubles, and the most popular library for creating them in Java is Mockito.

This lesson covers the Maven side (dependencies, scopes, plugin settings), the vocabulary of test doubles, the everyday Mockito calls, and a few pitfalls. Mockito itself needs a real build to run, which this site cannot do, so Mockito code is read-only. The runnable example is a plain Java stand-in that builds a tiny recording mock by hand, so you see exactly what a mock library automates.

The dependencies

Both libraries are used only by tests, so they belong in the test scope (see Dependency Scopes). Import the JUnit BOM for matching module versions (see Managing Versions) and add Mockito with its JUnit 5 extension:

XML
<properties>
  <junit.version>5.11.4</junit.version>
  <mockito.version>5.14.2</mockito.version>
</properties>

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.junit</groupId>
      <artifactId>junit-bom</artifactId>
      <version>${junit.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>${mockito.version}</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>${mockito.version}</version>
    <scope>test</scope>
  </dependency>
</dependencies>

The version numbers above are examples; look up current releases on Maven Central. mockito-core is the library; mockito-junit-jupiter adds MockitoExtension, which creates your @Mock fields and checks for mistakes. If you use Spring Boot, spring-boot-starter-test already includes JUnit, Mockito and AssertJ, so you do not list them again.

maven-surefire-plugin runs the tests. Use a recent version (see Core Plugins); with newer JDKs, Mockito's inline mock maker may print a warning that it is attaching an agent dynamically. The long-term fix is to give Surefire the Mockito agent through argLine, as described in Mockito's documentation for your JDK. It does not change test results.

Vocabulary: stub, mock, spy, fake

People say "mock" for everything, but the pieces differ:

Double Purpose
Dummy Fills a parameter and is never used
Stub Returns canned answers, so the class under test has input
Mock Records calls so a test can verify that a collaboration happened
Spy A real object with some methods stubbed or watched
Fake A working lightweight replacement, such as an in-memory repository

Prefer stubs and state checks (assert on the result) and use verification sparingly, for interactions that are the behavior, such as "an email was sent once".

A first test

Suppose this code under test, read-only:

Java
public class OrderService {
    private final PaymentGateway gateway;
    private final EmailSender emails;

    public OrderService(PaymentGateway gateway, EmailSender emails) {
        this.gateway = gateway;
        this.emails = emails;
    }

    public boolean placeOrder(String customer, int cents) {
        boolean paid = gateway.charge(customer, cents);
        if (paid) {
            emails.send(customer, "Order confirmed");
        }
        return paid;
    }
}

and the test, using JUnit 5 and Mockito (read-only):

Java
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {

    @Mock PaymentGateway gateway;
    @Mock EmailSender emails;

    @Test
    void sendsConfirmationWhenPaymentSucceeds() {
        when(gateway.charge("ana", 1500)).thenReturn(true);        // stub

        boolean result = new OrderService(gateway, emails).placeOrder("ana", 1500);

        assertTrue(result);                                         // state check
        verify(emails).send("ana", "Order confirmed");              // interaction check
    }

    @Test
    void sendsNothingWhenPaymentFails() {
        when(gateway.charge(anyString(), anyInt())).thenReturn(false);

        assertFalse(new OrderService(gateway, emails).placeOrder("ben", 900));

        verifyNoInteractions(emails);
    }
}

Things to notice:

  • @Mock plus MockitoExtension creates the mocks. You can also call mock(PaymentGateway.class) yourself.
  • when(...).thenReturn(...) stubs a method. Un-stubbed methods return defaults (false, 0, null, empty collections).
  • verify(mock).method(args) checks the call happened exactly once; verify(mock, times(2)), never() and atLeastOnce() adjust it. verifyNoInteractions checks that nothing was called.
  • Argument matchers such as anyString() and eq(...) are all-or-nothing: if one argument uses a matcher, all must (wrap the others in eq).
  • thenThrow(new IllegalStateException()) makes a stub fail, which tests error paths. For void methods use doThrow(...).when(mock).method().
  • With MockitoExtension, strict stubs are on: a stub the test never used fails the test with UnnecessaryStubbingException, which keeps tests tidy.

An ArgumentCaptor grabs what was passed, so you can assert on it:

Java
ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);
verify(emails).send(eq("ana"), message.capture());
assertTrue(message.getValue().contains("confirmed"));

What Mockito cannot do, and what not to mock

Mockito mocks classes and interfaces, and since version 5 can mock final classes through its inline mock maker. Static methods need mockStatic, which is a sign to reconsider the design. Do not mock types you do not own in bulk (a database driver, an HTTP client): wrap them in a small interface of your own and mock that, or use a fake or a real test container in an integration test (see Integration Tests with Failsafe). Never mock the class you are testing, and do not mock simple value objects, just create them.

A hand-built mock

A mock is not magic. It is an object that (1) returns programmed answers and (2) writes down every call. Here is a complete miniature version in plain Java, with a tiny assertion helper, so the Maven-run Mockito version above has no secrets left:

Java A recording mock and verification by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Mockito generates StubGateway and RecordingEmails for you at run time for any interface or class, adds matchers and flexible verification, and reports clear failure messages. Writing it by hand is still the right choice for small cases, and it shows that mocks are plain objects.

Running the tests

With the dependencies in place, the usual commands from The Command Line Toolbox apply:

Terminal
mvn test                            # compile and run all unit tests
mvn -Dtest=OrderServiceTest test    # one class
mvn -Dtest='OrderServiceTest#sendsNothingWhenPaymentFails' test
mvn verify                          # tests plus packaging and integration tests

Reports appear in target/surefire-reports. For a coverage report, add the JaCoCo plugin (see Code Quality: Coverage and Static Checks). In CI, the build fails when a test fails, which is the point (see Maven in CI and Faster Builds).

Practical advice

  • Keep unit tests fast: no network, no real database, no sleeping.
  • Name tests by behavior: sendsNothingWhenPaymentFails, not test2.
  • Arrange, act, assert: set up doubles, call one method, check results.
  • Verify behavior that matters, not every call; over-verified tests break on harmless refactoring.
  • Prefer constructor injection, as in OrderService; it makes classes easy to test.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Maven scope should Mockito and JUnit dependencies use?

    They are needed only to compile and run tests, so test scope keeps them out of the packaged artifact.
  2. 2. What does verify(emails).send("ana", "Order confirmed") check?

    verify defaults to times(1) and compares the recorded call with the expected arguments.
  3. 3. Which is a stub rather than a mock?

    A stub supplies programmed responses; a mock additionally records and verifies interactions.
  4. 4. With MockitoExtension, a stub the test never uses causes

    Strict stubs flag unused stubbing so tests stay precise.
  5. 5. Why should you avoid mocking types you do not own, such as a database driver?

    A thin wrapper you own gives a stable seam to mock, and real behavior is checked in integration tests.

Summary

  • Add junit-jupiter, mockito-core and mockito-junit-jupiter with test scope; manage versions with the JUnit BOM; Spring Boot's test starter bundles them.
  • Stubs give input, mocks record interactions, spies wrap real objects, fakes are lightweight working replacements.
  • Use @Mock, when/thenReturn, verify, matchers and ArgumentCaptor; prefer state assertions and verify only meaningful interactions.
  • Mock your own seams, not third-party types; use integration tests for real collaboration.
  • Run with mvn test or -Dtest=...; Surefire writes reports to target/surefire-reports.

Next: Integration Tests with Failsafe.