Skip to content
javahacks.dev
Testing

What to Mock and What to Leave Real in Your Java Tests

A rule for choosing what to mock in Java tests: replace what you do not own or cannot run cheaply, and keep real the code whose behavior you are testing.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the OpenJDK, JUnit5 and GitHub Actions logos.

Tests that mock everything break when you refactor and pass when the code is wrong. Tests that mock nothing are slow and flaky. The useful rule sits between them: replace what you cannot control, run what you can. This post turns that rule into a checklist for a Spring Boot service on JDK 25. The overall plan is in a practical Java testing strategy.

What a mock actually proves

A mock proves interaction: this method was called with these arguments. It does not prove the result is right, because you wrote the answer the mock gives.

java
when(prices.priceFor("sku-1")).thenReturn(100L);
assertEquals(200L, service.total("sku-1", 2));

This tests total's multiplication, with the mock supplying a price. That is fine, since the dependency is outside the unit. If prices were your own PriceCalculator with rules, mocking it would hide the very behavior that matters.

Mock these

BoundaryWhy
HTTP clients to other servicesSlow, flaky and out of your control
The clock (Clock, Instant.now())Time is an input; pass a fixed Clock
Random sources, id generatorsMake results deterministic
Third-party SDKs (payment, email)Cost money, need credentials
The file system and network, in unit testsIsolation

Prefer a hand-written fake to a mock when you can. A FakeMailer that records sent messages is clearer than five verify calls, and it keeps working when the interface gains a method.

Leave these real

  • Value objects and records. Construct them. new Money(100, "USD") is cheaper than a mock and cannot lie.
  • Your own pure domain logic. If it has no I/O, it is cheap to run and the point of the test.
  • Collections and the standard library. Mocking a List is a sign of a confused test.
  • The database. Run PostgreSQL in a container for repository tests. A mocked repository cannot find a wrong query, a missing index or a lazy-loading error; the H2 compromise accepts SQL that PostgreSQL rejects.

A worked comparison

Two ways to test an order service that applies a discount:

java
// Over-mocked: every collaborator is a mock, including the one that matters
@Mock DiscountPolicy policy;
@Mock Clock clock;
@Test
void appliesDiscount() {
    when(policy.percentFor(any())).thenReturn(10);
    service.total(order, customer);
    verify(policy).percentFor(customer);      // restates the implementation
}

// Better: real policy, fixed clock
@Test
void appliesWeekendDiscount() {
    var policy = new DiscountPolicy(Clock.fixed(Instant.parse("2026-03-14T10:00:00Z"), ZoneOffset.UTC));
    var service = new OrderService(policy);
    assertEquals(900, service.total(new Order(1_000), new Customer("ana")));
}

The second test checks the outcome and survives a refactoring that renames or reorders calls. The first fails whenever someone changes how the service asks the policy.

Signs you are mocking too much

  • The test has more when lines than assertions.
  • Changing a private implementation detail breaks the test.
  • Every test of a class verifies the same collaborator call.
  • The mock returns a mock.

A class that needs many mocks usually has too many dependencies; see the single responsibility discussion. Strict stubs flag unused ones: [UnnecessaryStubbingException](/library/unnecessarystubbingexception-fix-mockito-junit-5).

A fake is often better than a mock

A mock records calls and returns what it was told. A fake is a small working implementation, and tests that use one assert on the outcome and not on the conversation:

java
class InMemoryOrderRepository implements OrderRepository {

    private final Map<Long, Order> store = new HashMap<>();
    private long nextId = 1;

    @Override
    public Order save(Order order) {
        Order saved = order.withId(order.id() == null ? nextId++ : order.id());
        store.put(saved.id(), saved);
        return saved;
    }

    @Override
    public Optional<Order> findById(long id) {
        return Optional.ofNullable(store.get(id));
    }
}

A test that saves an order and loads it back passes whichever way the service calls the repository. A refactor that calls findById once instead of twice breaks a mock-based test with verify(times(2)), and breaks nothing here. Keep one fake per important port, and share it across tests. Check the fake against the real implementation with a contract test, run once against each, so the two cannot drift apart.

Control the clock and the randomness

Time and randomness are the two inputs that make a test pass today and fail tomorrow. Inject them and replace them with fixed values:

java
@Service
class DiscountService {

    private final Clock clock;

    DiscountService(Clock clock) {
        this.clock = clock;
    }

    boolean isWeekendSale() {
        DayOfWeek day = LocalDate.now(clock).getDayOfWeek();
        return day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY;
    }
}

DiscountService service = new DiscountService(
        Clock.fixed(Instant.parse("2026-03-14T10:00:00Z"), ZoneOffset.UTC));

The fixed clock gives a Saturday every time. The same holds for a UUID supplier or a Random seeded with a constant. These are the doubles worth writing, because there is no real alternative that behaves the same on two runs.

Use real infrastructure that you can start

A database is the clearest example. An embedded H2 database in place of PostgreSQL accepts SQL that PostgreSQL rejects and rejects SQL that it accepts, so tests pass for the wrong reasons. A container started by Testcontainers runs the real engine and costs a few seconds, once per test class or once per suite:

java
@Testcontainers
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class OrderRepositoryTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");
}

The @ServiceConnection annotation wires the data source to the container without properties. The test then covers the migration scripts, the dialect and the constraints, which a mocked repository can never do. See Testcontainers for Spring Boot.

A table to apply on Monday

DependencyTest withReason
Your own pure classesRealFast and deterministic
Your repositoriesReal database in a containerQueries and constraints are the behaviour
A remote HTTP serviceWireMock or a fake serverSlow, rate limited, out of your control
Payment, email, SMS providersA fake that records messagesThey cost money or reach real people
The clock, random, UUIDsInjected fixed valuesOtherwise the test changes over time
A message brokerA real broker in a container for integration, a fake for unitDelivery semantics matter
Another team's internal serviceA contract test plus a stubKeeps both sides honest

Mocks that give false confidence

A mock configured with when(repo.findById(1L)).thenReturn(order) proves that the service uses the value it was given. It does not prove that the real repository returns that value for id 1. A suite where every layer is mocked from the one above can be fully green on a broken application. At least one test per feature should run through the real stack from the controller to the database, with only the remote systems replaced.

Reviewing a test for what it would catch

A quick question applies to any test in review: what bug would make this fail? If the honest answer is "a typo in the test", the test is mostly a copy of the implementation. A test whose answer is "a change in how prices are rounded" or "a missing column in the migration" earns its place. Try the thought experiment with a mutation: change a comparison operator or remove a line in the code under test, and see whether any test fails. Tools such as PIT automate it and report the share of mutations that survive.

Tests that mock the collaborators of the class they test usually let most mutations survive, which is the measurable form of the warning that over-mocking gives false confidence.

Where the rule bends

A legacy class that calls a static singleton or reaches into the file system is hard to test without mocking; use the mocking tools to get a safety net, then refactor. The vocabulary of mocks, stubs, fakes and spies is in test doubles explained. The Mockito documentation covers the tools, and Martin Fowler's essay on mocks and stubs explains the classical and mockist schools.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.