Java Mock Objects

Su Suriya Ravichandran Updated 18 Nov 2026
15 min read ·Lesson 255 of 306

Java mock objects are stand-ins for real dependencies that let you test one class on its own. Besides plain mocks, there are stubs, fakes and spies, and each one fits a different testing need.

This lesson explains the kinds of test doubles, then goes beyond the basics of Mockito: dynamic answers with thenAnswer, partial mocks with spy, capturing arguments with ArgumentCaptor, checking call order with InOrder, the BDD style with given and then, mocking static methods with mockStatic, and controlling time with Clock. It ends with a subscription renewal test that combines a fake, mocks, a captor and a fixed clock. If when, verify and @Mock are new to you, read Mockito in Java first.


Types of Test Doubles

"Mock" is often used for any fake dependency, but there are five distinct kinds. Together they are called test doubles, like a stunt double that stands in for an actor.

TypeWhat it doesExample
DummyPassed in only to fill a parameter; never usedA null logger the test path never touches
StubReturns fixed answers to callsA price service that always returns 499.00
FakeA working but simplified implementationAn in-memory repository backed by a HashMap
SpyA real object that also records calls; selected methods can be overriddenA real ArrayList wrapped with spy()
MockPre-programmed with expectations and verified afterwardsA PaymentGateway mock checked with verify()

Mockito creates stubs, spies and mocks. Fakes are usually written by hand, as the next section shows.


Write a Fake for Stateful Dependencies

A fake is real code, just simpler than production code. Fakes work well for repositories, where a test needs to save something and read it back. Stubbing that with when for every call would be long and brittle.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;

interface UserRepository {
    void save(String email, String name);
    Optional<String> findName(String email);
}

// Fake: a real, in-memory implementation used only in tests
class InMemoryUserRepository implements UserRepository {
    private final Map<String, String> namesByEmail = new HashMap<>();

    @Override
    public void save(String email, String name) {
        namesByEmail.put(email.toLowerCase(), name);
    }

    @Override
    public Optional<String> findName(String email) {
        return Optional.ofNullable(namesByEmail.get(email.toLowerCase()));
    }
}

class RegistrationService {
    private final UserRepository users;

    RegistrationService(UserRepository users) {
        this.users = users;
    }

    boolean register(String email, String name) {
        if (users.findName(email).isPresent()) {
            return false; // already registered
        }
        users.save(email, name);
        return true;
    }
}

class RegistrationServiceTest {

    @Test
    void secondRegistrationWithSameEmailIsRejected() {
        UserRepository users = new InMemoryUserRepository();
        RegistrationService service = new RegistrationService(users);

        assertTrue(service.register("asha@example.com", "Asha"));
        assertFalse(service.register("ASHA@example.com", "Asha K"));
        assertEquals(Optional.of("Asha"), users.findName("asha@example.com"));
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • InMemoryUserRepository really stores data, so register can save a user and later find it, just as it would with a database.
  • The test checks behaviour across calls (register twice), which is natural with a fake and awkward with stubbing.
  • A fake is reusable across many test classes. Keep it in src/test/java so it never ships with the application.

Compute Return Values With thenAnswer

thenReturn always returns a fixed value. thenAnswer runs a lambda on every call, so the return value can depend on the arguments.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;

class ThenAnswerTest {

    interface TaxService {
        long taxInPaise(String state, long amountInPaise);
    }

    interface IdService {
        String newId(String prefix);
    }

    @Test
    void taxDependsOnTheAmount() {
        TaxService taxService = mock(TaxService.class);
        when(taxService.taxInPaise(anyString(), anyLong()))
                .thenAnswer(invocation -> {
                    long amount = invocation.getArgument(1);
                    return amount * 18 / 100; // flat 18 % for the test
                });

        assertEquals(18_000, taxService.taxInPaise("TN", 100_000));
        assertEquals(9_000, taxService.taxInPaise("KA", 50_000));
    }

    @Test
    void generatesSequentialIds() {
        IdService idService = mock(IdService.class);
        AtomicLong counter = new AtomicLong(1000);
        when(idService.newId(anyString()))
                .thenAnswer(invocation -> invocation.getArgument(0) + "-" + counter.incrementAndGet());

        assertEquals("ORD-1001", idService.newId("ORD"));
        assertEquals("INV-1002", idService.newId("INV"));
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • The invocation object gives access to the call. getArgument(1) returns the second argument, already cast to the type you assign it to.
  • In the first test the answer is calculated from the amount, so one stub covers every amount.
  • In the second test the lambda keeps state in an AtomicLong, producing a new ID on each call while still using the prefix that was passed in.

Partial Mocks With spy()

A spy wraps a real object. Calls go to the real methods unless you stub them. Spies are useful when you want real behaviour but need to override one method or check how the object was used.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;

class SpyTest {

    @Test
    void spyCallsRealMethodsAndRecordsThem() {
        List<String> courses = spy(new ArrayList<>());

        courses.add("Java");
        courses.add("Python");

        assertEquals(2, courses.size());       // real size
        assertEquals("Java", courses.get(0));  // real element
        verify(courses).add("Python");         // calls were recorded
    }

    @Test
    void stubOneMethodOnASpy() {
        List<String> courses = spy(new ArrayList<>());
        courses.add("Java");

        doReturn(1_000).when(courses).size();     // override just this method
        doReturn("Go").when(courses).get(5);      // index 5 does not exist in the real list

        assertEquals(1_000, courses.size());
        assertEquals("Go", courses.get(5));
        assertEquals("Java", courses.get(0));     // other calls stay real
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • spy(new ArrayList<>()) creates a copy of the list that behaves exactly like a real ArrayList but records every call.
  • On a spy, always stub with doReturn(...).when(spy).method(). Writing when(courses.get(5)) would call the real get(5) first, which throws IndexOutOfBoundsException before Mockito can stub it.
  • Use spies sparingly. If you need to stub many methods of a class, a plain mock or a fake is usually clearer.

Capture Arguments With ArgumentCaptor

verify with matchers checks that a call happened. When you need to inspect the object that was passed, for example the full email a service built, use an ArgumentCaptor.

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class WelcomeEmailTest {

    record Email(String to, String subject, String body) {}

    interface Mailer {
        void send(Email email);
    }

    static class WelcomeService {
        private final Mailer mailer;

        WelcomeService(Mailer mailer) {
            this.mailer = mailer;
        }

        void welcome(String name, String email, List<String> courses) {
            String body = "Hi " + name + ", you are enrolled in: " + String.join(", ", courses);
            mailer.send(new Email(email, "Welcome to GOCOURSE", body));
        }
    }

    @Mock
    Mailer mailer;

    @Captor
    ArgumentCaptor<Email> emailCaptor;

    @Test
    void buildsTheWelcomeEmail() {
        new WelcomeService(mailer).welcome("Asha", "asha@example.com", List.of("Java", "Python"));

        verify(mailer).send(emailCaptor.capture());
        Email sent = emailCaptor.getValue();

        assertAll(
                () -> assertEquals("asha@example.com", sent.to()),
                () -> assertEquals("Welcome to GOCOURSE", sent.subject()),
                () -> assertTrue(sent.body().contains("Java, Python")));
        System.out.println(sent);
    }

    @Test
    void capturesEveryCall() {
        WelcomeService service = new WelcomeService(mailer);
        service.welcome("Asha", "asha@example.com", List.of("Java"));
        service.welcome("Ravi", "ravi@example.com", List.of("Go"));

        verify(mailer, times(2)).send(emailCaptor.capture());
        List<String> recipients = emailCaptor.getAllValues().stream().map(Email::to).toList();

        assertEquals(List.of("asha@example.com", "ravi@example.com"), recipients);
    }
}

Output (from the println in the first test):

Email[to=asha@example.com, subject=Welcome to GOCOURSE, body=Hi Asha, you are enrolled in: Java, Python]

How it works:

  • @Captor creates a typed ArgumentCaptor<Email>. Without the annotation you would write ArgumentCaptor.forClass(Email.class).
  • emailCaptor.capture() is used inside verify, where it acts like a matcher that accepts any Email and stores it.
  • getValue() returns the last captured argument, and getAllValues() returns all of them in call order.

Note: Use captors in verify, not in when. To control return values based on arguments, use thenAnswer or a matcher instead.


Verify Call Order With InOrder

Some rules depend on order: charge the card before marking an order as paid, or open a connection before writing. InOrder verifies calls in sequence, even across several mocks.

import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;

import org.junit.jupiter.api.Test;
import org.mockito.InOrder;

class InOrderTest {

    interface PaymentGateway { void charge(String orderId); }
    interface OrderRepository { void markPaid(String orderId); }
    interface Mailer { void sendReceipt(String orderId); }

    void completeOrder(String orderId, PaymentGateway gateway, OrderRepository orders, Mailer mailer) {
        gateway.charge(orderId);
        orders.markPaid(orderId);
        mailer.sendReceipt(orderId);
    }

    @Test
    void chargesBeforeMarkingPaidAndEmailing() {
        PaymentGateway gateway = mock(PaymentGateway.class);
        OrderRepository orders = mock(OrderRepository.class);
        Mailer mailer = mock(Mailer.class);

        completeOrder("ORD-1", gateway, orders, mailer);

        InOrder inOrder = inOrder(gateway, orders, mailer);
        inOrder.verify(gateway).charge("ORD-1");
        inOrder.verify(orders).markPaid("ORD-1");
        inOrder.verify(mailer).sendReceipt("ORD-1");
    }
}

If completeOrder sent the receipt before charging, the test would fail with a message like:

Verification in order failure
Wanted but not invoked:
mailer.sendReceipt("ORD-1");
-> at com.gocourse.InOrderTest.chargesBeforeMarkingPaidAndEmailing(InOrderTest.java:31)
Wanted anywhere AFTER following interaction:
orders.markPaid("ORD-1");

How it works:

  • inOrder(gateway, orders, mailer) creates a verifier that knows the global order of calls on those three mocks.
  • Each inOrder.verify(...) must match a call that happened after the previously verified one.
  • Calls that you do not verify are ignored, so you only need to list the steps whose order matters.

Write Readable Tests With BDDMockito

BDD (behaviour-driven development) tests are written as given / when / then. BDDMockito offers aliases that match this style: given(...).willReturn(...) instead of when(...).thenReturn(...), and then(mock).should() instead of verify(mock).

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;

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 CouponBddTest {

    interface CouponRepository {
        int discountPercent(String code);
        void markUsed(String code);
    }

    long applyCoupon(CouponRepository coupons, String code, long amountInPaise) {
        int percent = coupons.discountPercent(code);
        if (percent == 0) {
            return amountInPaise;
        }
        coupons.markUsed(code);
        return amountInPaise - amountInPaise * percent / 100;
    }

    @Mock
    CouponRepository coupons;

    @Test
    void validCouponReducesPriceAndIsMarkedUsed() {
        // given
        given(coupons.discountPercent("GOCOURSE10")).willReturn(10);

        // when
        long price = applyCoupon(coupons, "GOCOURSE10", 49_900);

        // then
        assertEquals(44_910, price);
        then(coupons).should().markUsed("GOCOURSE10");
    }

    @Test
    void unknownCouponChangesNothing() {
        given(coupons.discountPercent("FREE100")).willReturn(0);

        assertEquals(49_900, applyCoupon(coupons, "FREE100", 49_900));
        then(coupons).should(never()).markUsed("FREE100");
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • given and then are the same as when and verify; only the names change. They avoid the confusing double meaning of "when" in a given/when/then test.
  • 10 % off 499.00 is 449.10, which is 44_910 paise.
  • Both styles can be mixed, but most teams pick one and use it everywhere.

Mock Static Methods and Control Time

Static methods cannot be replaced by passing a different object. Mockito's mockStatic can override them temporarily inside a try-with-resources block.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mockStatic;

import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;

class StaticMockTest {

    static class OrderIds {
        static String next() {
            return "ORD-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        }
    }

    String createInvoiceHeader(String customer) {
        return "Invoice " + OrderIds.next() + " for " + customer;
    }

    @Test
    void usesAFixedOrderIdInsideTheBlock() {
        try (MockedStatic<OrderIds> mocked = mockStatic(OrderIds.class)) {
            mocked.when(OrderIds::next).thenReturn("ORD-TEST01");

            assertEquals("Invoice ORD-TEST01 for Asha", createInvoiceHeader("Asha"));
            mocked.verify(OrderIds::next);
        }

        // outside the block, the real static method is back
        assertTrue(createInvoiceHeader("Asha").matches("Invoice ORD-[0-9A-F]{8} for Asha"));
    }
}

Output (mvn test, shortened):

[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

How it works:

  • mockStatic(OrderIds.class) replaces every static method of OrderIds on the current thread until the MockedStatic is closed.
  • mocked.when(OrderIds::next) stubs the static method, and mocked.verify checks that it was called.
  • When the try block ends, close() restores the real method, which the last assertion proves.

For time, avoid static mocking entirely. Pass a java.time.Clock into your class and use Clock.fixed in tests:

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import org.junit.jupiter.api.Test;

class ClockTest {

    record Trial(LocalDate endsOn) {
        boolean isExpired(Clock clock) {
            return LocalDate.now(clock).isAfter(endsOn);
        }
    }

    @Test
    void trialExpiresTheDayAfterItEnds() {
        Clock nov17 = Clock.fixed(Instant.parse("2026-11-17T10:00:00Z"), ZoneId.of("Asia/Kolkata"));
        Clock nov18 = Clock.fixed(Instant.parse("2026-11-18T10:00:00Z"), ZoneId.of("Asia/Kolkata"));
        Trial trial = new Trial(LocalDate.of(2026, 11, 17));

        assertEquals(LocalDate.of(2026, 11, 17), LocalDate.now(nov17));
        assertFalse(trial.isExpired(nov17));
        assertTrue(trial.isExpired(nov18));
    }
}

This test passes on any day it is run, because LocalDate.now(clock) reads the fixed instant instead of the system time. 10:00 UTC is 15:30 in India, so the date is 17 November in both zones.

Note: Needing mockStatic is often a sign that a dependency should be passed in instead. Prefer injecting an object such as Clock or an ID generator, and keep mockStatic for code you cannot change.


Real-World Example: Java Mock Objects for Subscription Renewals

A course platform renews monthly subscriptions every day. The service finds subscriptions due today, charges each customer, saves the new renewal date, and emails the result. This test uses every kind of double from the lesson:

DependencyTest doubleWhy
SubscriptionRepositoryFake (InMemorySubscriptionRepository)Tests need to save and read back state
PaymentGatewayMock with thenReturn, thenThrow, thenAnswerControls approvals and declines
MailerMock + ArgumentCaptorTests inspect the emails that were built
ClockClock.fixed"Today" is always 17 November 2026
package com.gocourse.subscriptions;

import java.time.Clock;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

public record Subscription(String id, String customerId, String email,
                           long priceInPaise, LocalDate renewsOn, boolean active) {

    Subscription renewedUntil(LocalDate nextDate) {
        return new Subscription(id, customerId, email, priceInPaise, nextDate, true);
    }

    Subscription deactivated() {
        return new Subscription(id, customerId, email, priceInPaise, renewsOn, false);
    }
}

interface SubscriptionRepository {
    List<Subscription> findDueOn(LocalDate date);
    Optional<Subscription> findById(String id);
    void save(Subscription subscription);
}

interface PaymentGateway {
    /** Returns a transaction id, or throws PaymentDeclinedException. */
    String charge(String customerId, long amountInPaise);
}

class PaymentDeclinedException extends RuntimeException {
    PaymentDeclinedException(String reason) {
        super(reason);
    }
}

record Email(String to, String subject, String body) {}

interface Mailer {
    void send(Email email);
}

class RenewalService {
    private final SubscriptionRepository repository;
    private final PaymentGateway gateway;
    private final Mailer mailer;
    private final Clock clock;

    RenewalService(SubscriptionRepository repository, PaymentGateway gateway, Mailer mailer, Clock clock) {
        this.repository = repository;
        this.gateway = gateway;
        this.mailer = mailer;
        this.clock = clock;
    }

    int renewDueSubscriptions() {
        LocalDate today = LocalDate.now(clock);
        int renewed = 0;
        for (Subscription sub : repository.findDueOn(today)) {
            try {
                String transactionId = gateway.charge(sub.customerId(), sub.priceInPaise());
                LocalDate next = sub.renewsOn().plusMonths(1);
                repository.save(sub.renewedUntil(next));
                mailer.send(new Email(sub.email(), "Subscription renewed",
                        "Transaction " + transactionId + ". Next renewal on " + next + "."));
                renewed++;
            } catch (PaymentDeclinedException e) {
                repository.save(sub.deactivated());
                mailer.send(new Email(sub.email(), "Payment failed",
                        "We could not renew your subscription: " + e.getMessage()));
            }
        }
        return renewed;
    }
}
package com.gocourse.subscriptions;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
@DisplayName("RenewalService")
class RenewalServiceTest {

    static class InMemorySubscriptionRepository implements SubscriptionRepository {
        private final Map<String, Subscription> byId = new HashMap<>();

        @Override
        public List<Subscription> findDueOn(LocalDate date) {
            return byId.values().stream()
                    .filter(s -> s.active() && s.renewsOn().equals(date))
                    .sorted((a, b) -> a.id().compareTo(b.id()))
                    .toList();
        }

        @Override
        public Optional<Subscription> findById(String id) {
            return Optional.ofNullable(byId.get(id));
        }

        @Override
        public void save(Subscription subscription) {
            byId.put(subscription.id(), subscription);
        }
    }

    private static final LocalDate TODAY = LocalDate.of(2026, 11, 17);
    private static final Clock FIXED_CLOCK =
            Clock.fixed(Instant.parse("2026-11-17T03:30:00Z"), ZoneId.of("Asia/Kolkata"));

    @Mock PaymentGateway gateway;
    @Mock Mailer mailer;
    @Captor ArgumentCaptor<Email> emailCaptor;

    private InMemorySubscriptionRepository repository;
    private RenewalService service;

    @BeforeEach
    void setUp() {
        repository = new InMemorySubscriptionRepository();
        repository.save(new Subscription("SUB-1", "CUST-1", "asha@example.com", 49_900, TODAY, true));
        repository.save(new Subscription("SUB-2", "CUST-2", "ravi@example.com", 99_900, TODAY.plusDays(14), true));
        service = new RenewalService(repository, gateway, mailer, FIXED_CLOCK);
    }

    @Test
    @DisplayName("charges, extends and emails a subscription due today")
    void renewsDueSubscription() {
        when(gateway.charge("CUST-1", 49_900)).thenReturn("TXN-1001");

        assertEquals(1, service.renewDueSubscriptions());

        Subscription renewed = repository.findById("SUB-1").orElseThrow();
        assertEquals(LocalDate.of(2026, 12, 17), renewed.renewsOn());

        InOrder inOrder = inOrder(gateway, mailer);
        inOrder.verify(gateway).charge("CUST-1", 49_900);
        inOrder.verify(mailer).send(emailCaptor.capture());

        Email email = emailCaptor.getValue();
        assertAll(
                () -> assertEquals("asha@example.com", email.to()),
                () -> assertEquals("Subscription renewed", email.subject()),
                () -> assertEquals("Transaction TXN-1001. Next renewal on 2026-12-17.", email.body()));

        verify(gateway, never()).charge(eq("CUST-2"), anyLong()); // not due yet
    }

    @Test
    @DisplayName("deactivates the subscription and explains why when payment is declined")
    void declinedPayment() {
        when(gateway.charge("CUST-1", 49_900)).thenThrow(new PaymentDeclinedException("Card expired"));

        assertEquals(0, service.renewDueSubscriptions());

        Subscription afterRun = repository.findById("SUB-1").orElseThrow();
        assertFalse(afterRun.active());
        assertEquals(TODAY, afterRun.renewsOn());

        verify(mailer).send(emailCaptor.capture());
        assertEquals("Payment failed", emailCaptor.getValue().subject());
        assertTrue(emailCaptor.getValue().body().endsWith("Card expired"));
    }

    @Test
    @DisplayName("renews several subscriptions and gives each its own transaction")
    void renewsSeveral() {
        repository.save(new Subscription("SUB-3", "CUST-3", "meena@example.com", 29_900, TODAY, true));
        when(gateway.charge(anyString(), anyLong()))
                .thenAnswer(invocation -> "TXN-" + invocation.getArgument(0, String.class));

        assertEquals(2, service.renewDueSubscriptions());

        verify(mailer, times(2)).send(emailCaptor.capture());
        List<String> bodies = emailCaptor.getAllValues().stream().map(Email::body).toList();
        assertEquals(List.of(
                "Transaction TXN-CUST-1. Next renewal on 2026-12-17.",
                "Transaction TXN-CUST-3. Next renewal on 2026-12-17."), bodies);
    }

    @Test
    @DisplayName("does nothing on a day with no renewals")
    void nothingDue() {
        Clock nextDay = Clock.fixed(Instant.parse("2026-11-18T03:30:00Z"), ZoneId.of("Asia/Kolkata"));
        RenewalService tomorrow = new RenewalService(repository, gateway, mailer, nextDay);

        assertEquals(0, tomorrow.renewDueSubscriptions());
        verify(gateway, never()).charge(anyString(), anyLong());
        verify(mailer, never()).send(org.mockito.ArgumentMatchers.any());
    }
}

Output in the Console Launcher:

└─ RenewalService ✔
   ├─ charges, extends and emails a subscription due today ✔
   ├─ deactivates the subscription and explains why when payment is declined ✔
   ├─ renews several subscriptions and gives each its own transaction ✔
   └─ does nothing on a day with no renewals ✔

[ 4 tests successful ]
[ 0 tests failed ]

How it works:

  1. A fake for state. InMemorySubscriptionRepository stores real Subscription records. The tests read back the saved state, such as the new renewal date of 17 December, which would be awkward to check with a mocked repository. It sorts by ID so the order of emails is predictable.
  2. A fixed clock. 03:30 UTC is 09:00 in India, so "today" is always 17 November 2026, whatever day the tests run. The last test uses a second clock to simulate the next day without waiting.
  3. Mocks for side effects. PaymentGateway and Mailer talk to outside systems, so they are mocks. thenReturn approves a payment, thenThrow declines one, and thenAnswer builds a different transaction ID for each customer.
  4. Captured emails. ArgumentCaptor gives the test the actual Email records, so it checks the exact subject and body text customers would see. getAllValues() checks both emails in the multi-renewal test.
  5. Order and absence. InOrder proves the customer is charged before the confirmation is sent. never() proves that CUST-2, who is not due yet, is never charged.

Each double does the job it is best at, and the tests describe the renewal rules clearly without a database, a bank or a mail server. To learn more about the fixtures used in setUp, see JUnit Test Fixtures.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Mock Objects and get answers drawn from it.

Signed-in readers only.