Java Mock Objects
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.
| Type | What it does | Example |
|---|---|---|
| Dummy | Passed in only to fill a parameter; never used | A null logger the test path never touches |
| Stub | Returns fixed answers to calls | A price service that always returns 499.00 |
| Fake | A working but simplified implementation | An in-memory repository backed by a HashMap |
| Spy | A real object that also records calls; selected methods can be overridden | A real ArrayList wrapped with spy() |
| Mock | Pre-programmed with expectations and verified afterwards | A 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:
InMemoryUserRepositoryreally stores data, soregistercan 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/javaso 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
invocationobject 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 realArrayListbut records every call.- On a spy, always stub with
doReturn(...).when(spy).method(). Writingwhen(courses.get(5))would call the realget(5)first, which throwsIndexOutOfBoundsExceptionbefore 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:
@Captorcreates a typedArgumentCaptor<Email>. Without the annotation you would writeArgumentCaptor.forClass(Email.class).emailCaptor.capture()is used insideverify, where it acts like a matcher that accepts anyEmailand stores it.getValue()returns the last captured argument, andgetAllValues()returns all of them in call order.
Note: Use captors in
verify, not inwhen. To control return values based on arguments, usethenAnsweror 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:
givenandthenare the same aswhenandverify; 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_910paise. - 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 ofOrderIdson the current thread until theMockedStaticis closed.mocked.when(OrderIds::next)stubs the static method, andmocked.verifychecks 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
mockStaticis often a sign that a dependency should be passed in instead. Prefer injecting an object such asClockor an ID generator, and keepmockStaticfor 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:
| Dependency | Test double | Why |
|---|---|---|
SubscriptionRepository | Fake (InMemorySubscriptionRepository) | Tests need to save and read back state |
PaymentGateway | Mock with thenReturn, thenThrow, thenAnswer | Controls approvals and declines |
Mailer | Mock + ArgumentCaptor | Tests inspect the emails that were built |
Clock | Clock.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:
- A fake for state.
InMemorySubscriptionRepositorystores realSubscriptionrecords. 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. - A fixed clock.
03:30 UTCis09:00in 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. - Mocks for side effects.
PaymentGatewayandMailertalk to outside systems, so they are mocks.thenReturnapproves a payment,thenThrowdeclines one, andthenAnswerbuilds a different transaction ID for each customer. - Captured emails.
ArgumentCaptorgives the test the actualEmailrecords, so it checks the exact subject and body text customers would see.getAllValues()checks both emails in the multi-renewal test. - Order and absence.
InOrderproves the customer is charged before the confirmation is sent.never()proves thatCUST-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.