Testing in Machine Coding

In a 90-minute machine-coding round you will not write comprehensive tests, and advice that assumes you will is advice from someone who has not sat the round. What you will do is three things: design classes that could be tested, write a runnable demo that proves the happy path and two edge cases through its output rather than through your narration, and answer “how would you test this?” with specifics instead of the word “mocks”.

Why this matters: testability is not an axis graded after correctness – it is how the interviewer sees your correctness, since a class that reaches for LocalDateTime.now() and a singleton gateway cannot be demonstrated at all. Many interviewers also weight a main that walks every requirement above a half-finished JUnit suite, because the first proves the system works and the second proves nothing yet. So ask at minute 2 which they would rather have: the answer changes your plan, and asking scores by itself.


Prerequisites

  • Machine Coding Round – the 90-minute budget whose last 20 minutes this lesson spends
  • Dependency Injection – testability is the entire payoff of DI, and this is what the payoff looks like
  • Concurrency – the latch test below is how you show a lock actually holds

The Problem: the design that cannot be tested, and the demo that proves nothing

Two failures that travel together. First, a BookingService that creates or reaches for every collaborator inside the method that needs it:

public class BookingService {
    // No constructor, no fields. Every dependency is fetched in place.
    public Booking book(String showId, String seat, String user, long amountMinor) {
        String bookingId = "BKG-" + new Random().nextInt(1_000_000);        // (1)
        LocalDateTime bookedAt = LocalDateTime.now();                       // (2)
        if (bookedAt.getHour() >= 22) amountMinor = amountMinor * 80 / 100; // a real rule

        if (!PaymentGateway.getInstance().charge(bookingId, amountMinor))   // (3)
            throw new PaymentFailedException(bookingId);

        return BookingDatabase.getInstance().save(
            new Booking(bookingId, showId, seat, user, amountMinor, bookedAt));
    }
}

// And the demo that ships with it.                                         // (4)
public static void main(String[] args) {
    BookingService service = new BookingService();
    System.out.println(service.book("SHOW-7", "4C", "alice", 25000));
    System.out.println(service.book("SHOW-7", "4C", "bob",   25000)); // 4C sold twice
    System.out.println("Done.");
}

Four lines, four kinds of damage:

  1. new Random() means the output is never the same twice. You cannot assert on a booking id, reproduce a run the interviewer asks about, or force the collision an id generator exists to prevent.
  2. LocalDateTime.now() makes the discount branch unreachable. It fires between 22:00 and midnight, so in a daytime interview no input reaches that line – and a test written at 23:30 passes once, then fails every morning in CI.
  3. getInstance() hard-wires the collaborator at compile time. No seam, so no way to hand the service a card that declines or an empty repository, which is where the interesting code lives (Singleton covers the rest of that bill).
  4. The demo asserts nothing, so a wrong answer scrolls past. Line two double-books 4C, yet a working system and a broken one both print Booking@3f8a... and the word Done. The fix is one line per step: print the label, the expected value and the actual value together.

💡 Seam = a place where you can substitute different behaviour without editing the class: a constructor parameter, an interface, an overridable method. No seam, no test. Learn more →

Both failures cost marks. An untestable class loses them even when its logic is right, because the interviewer cannot watch it work; and a demo without assertions makes the regression you introduce at minute 70 invisible until the interviewer finds it.


The 20-minute test budget

Assume the honest case: minute 70 of 90, the core flow runs, twenty minutes left. Spend them in this order and stop wherever the clock stops you – each step is worth more than every step beneath it, which is roughly the reverse of how most candidates work.

  1. A runnable demo exercising every functional requirement in order. One labelled line per step printing expected versus actual, so a failure is visible without anyone reading code: [3] double-book 4C expected=REJECTED actual=REJECTED. The requirements were a numbered list in the problem statement, and the demo should be that list, executed. If you deliver nothing else, deliver this.

  2. The one or two invariants the problem is actually about. Not “does getSeat() return the seat” – money is conserved across a split, no seat is held by two bookings, stock never goes negative. One invariant test beats ten getter tests for a concrete reason: a getter test can only fail if you broke that getter, while an invariant test fails if you broke anything on the path to it, so double-booking, lost updates and rounding bugs all surface through that single assertion.

    💡 Invariant = a statement that must hold after every operation, whatever the order or interleaving: balances sum to zero, seats never double-book, stock is never negative.

  3. The edge cases the requirements already imply. Inventing cases burns ten minutes; walk the signature instead. The empty collection, the single element, the boundary value (last free seat, exact balance, final slot), the duplicate submission, and the case the requirements explicitly reject – that last group yields most, because rejection paths are where code throws NullPointerException instead of the domain exception you declared (Exception Handling).

  4. One concurrency test if the problem is concurrent, and be honest about what it proves. A loop of 1000 threads that happens to pass proves close to nothing: the interleaving you fear may not have occurred, and the same test passes against code with no lock at all. The valuable version is deterministic by construction – park N threads on a latch, release them together, assert exactly one won – and you validate it by deleting the lock and checking it goes red.

  5. Only now, unit tests on individual strategies. A pricing Strategy or a split calculator is a pure function of its inputs, so its tests are the easiest to write and explain – which is exactly why they come last.

If the clock beats you at step 2, say so and say what came next: “the suite stops at the double-booking invariant; next would be the declined-payment rollback and the simultaneous claim.” Naming the untested cases earns most of the credit for testing them.


Real-World Example: a Booking Service and Its Tests

The same service with three seams – a Clock, an IdGenerator and a PaymentGateway, all handed in by the constructor (Dependency Injection). FakePaymentGateway is the piece to study: it records the calls it received and has real behaviour, which is what lets one small class serve both the invariant test and the rollback test.

public interface IdGenerator { String next(); }
public interface PaymentGateway { PaymentResult charge(String bookingId, Money amount); }

public class BookingService {
    private final BookingRepository repo;  private final IdGenerator ids;
    private final PaymentGateway gateway;  private final Clock clock;

    public BookingService(BookingRepository repo, PaymentGateway gateway,
                          IdGenerator ids, Clock clock) {
        this.repo = repo; this.gateway = gateway; this.ids = ids; this.clock = clock;
    }

    public Booking book(String showId, String seat, String user, Money price) {
        if (!repo.claimSeat(showId, seat))      // the atomic claim IS the invariant
            throw new SeatUnavailableException(showId, seat);

        Instant now = clock.instant();          // injected, therefore assertable
        int hour = LocalDateTime.ofInstant(now, ZoneOffset.UTC).getHour();
        Money due = hour >= 22 ? price.percent(80) : price;

        String id = ids.next();
        PaymentResult result = gateway.charge(id, due);
        if (!result.isSuccessful()) {
            repo.releaseSeat(showId, seat);     // compensate, or the seat leaks
            throw new PaymentFailedException(result.reason());
        }
        Booking b = new Booking(id, showId, seat, user, due, now);
        repo.save(b);
        return b;
    }
}

// The fake: records calls AND has real behaviour.
public class FakePaymentGateway implements PaymentGateway {
    private final List<String> charged = new CopyOnWriteArrayList<>();  // spy half
    private final AtomicLong balanceMinor = new AtomicLong(500_000);    // fake half
    private volatile boolean failNext = false;

    public void failNextCharge() { this.failNext = true; }

    @Override public PaymentResult charge(String bookingId, Money amount) {
        charged.add(bookingId);
        if (failNext) { failNext = false; return PaymentResult.declined("DECLINED"); }
        balanceMinor.addAndGet(-amount.minorUnits());     // real behaviour, so the
        return PaymentResult.ok("TXN-" + charged.size()); // test can assert money
    }
    public long balanceMinor() { return balanceMinor.get(); }  // prefer this one
    public int chargeCount()   { return charged.size(); }
}

// newKeySet().add() is an atomic test-and-set: false if the key was there.
public class InMemoryBookingRepository implements BookingRepository {
    private final Set<String> claimed = ConcurrentHashMap.newKeySet();
    private final List<Booking> saved = new CopyOnWriteArrayList<>();

    @Override public boolean claimSeat(String sh, String st) { return claimed.add(sh + st); }
    @Override public void releaseSeat(String sh, String st) { claimed.remove(sh + st); }
    @Override public void save(Booking b) { saved.add(b); }
    public long countFor(String st) {
        return saved.stream().filter(b -> b.seat().equals(st)).count();
    }
}

class BookingServiceTest {
    static final Instant NOON = Instant.parse("2026-03-14T12:00:00Z");
    static final Instant LATE = Instant.parse("2026-03-14T22:30:00Z");
    static final Money PRICE  = Money.ofMinor(25_000);

    InMemoryBookingRepository repo = new InMemoryBookingRepository();
    FakePaymentGateway gateway = new FakePaymentGateway();
    BookingService service = serviceAt(NOON);

    BookingService serviceAt(Instant t) {
        return new BookingService(repo, gateway, new SequentialIdGenerator("BKG"),
                                  Clock.fixed(t, ZoneOffset.UTC));
    }

    @Test void oneSeatYieldsExactlyOneBooking() {      // THE INVARIANT
        service.book("SHOW-7", "4C", "alice", PRICE);
        assertThrows(SeatUnavailableException.class,
                     () -> service.book("SHOW-7", "4C", "bob", PRICE));
        assertEquals(1, repo.countFor("4C"));
        assertEquals(1, gateway.chargeCount());        // bob was never charged
    }

    @Test void declinedPaymentReleasesTheSeatAndMovesNoMoney() {
        gateway.failNextCharge();                      // the fake, told to fail
        assertThrows(PaymentFailedException.class,
                     () -> service.book("SHOW-7", "4C", "alice", PRICE));
        assertEquals(500_000, gateway.balanceMinor()); // money conserved
        service.book("SHOW-7", "4C", "bob", PRICE);    // and the seat came back
    }

    @Test void lateShowsAreDiscounted() {  // unreachable before the Clock was a seam
        Booking b = serviceAt(LATE).book("SHOW-7", "4C", "alice", PRICE);
        assertEquals(Money.ofMinor(20_000), b.amount());
        assertEquals(LATE, b.bookedAt());
    }

    // A collision you forced, not one you hoped for: line up, start together,
    // finish or fail fast.
    @Test void exactlyOneOfTwentyConcurrentClaimsWins() throws Exception {
        int n = 20;
        CountDownLatch atTheLine = new CountDownLatch(n), go = new CountDownLatch(1);
        CountDownLatch finished = new CountDownLatch(n);
        AtomicInteger wins = new AtomicInteger(), rejected = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(n);

        for (int i = 0; i < n; i++) {
            String user = "user-" + i;
            pool.execute(() -> {
                atTheLine.countDown();
                try {
                    go.await();              // every thread parks HERE
                    service.book("SHOW-7", "4C", user, PRICE);
                    wins.incrementAndGet();
                } catch (SeatUnavailableException e) { rejected.incrementAndGet(); }
                  catch (InterruptedException e) { Thread.currentThread().interrupt(); }
                finally { finished.countDown(); }
            });
        }
        atTheLine.await();  // all 20 exist and are blocked, not merely submitted
        go.countDown();     // released within microseconds of each other
        assertTrue(finished.await(5, TimeUnit.SECONDS), "did not finish: deadlock");
        pool.shutdownNow();

        assertEquals(1, wins.get());            // totals, never WHICH thread won
        assertEquals(n - 1, rejected.get());
        assertEquals(1, repo.countFor("4C"));   // and nobody was charged twice
    }
}
from datetime import datetime, timezone

import pytest

NOON = datetime(2026, 3, 14, 12, 0, tzinfo=timezone.utc)
PRICE = 25_000


class FakePaymentGateway:
    """Duck-typed, no ABC and no mock library: records the calls it saw AND
    runs a real balance rule."""

    def __init__(self, balance_minor: int = 500_000) -> None:
        self.charges: list[str] = []            # the spy half
        self.balance_minor = balance_minor      # the fake half
        self._fail_next = False

    def fail_next_charge(self) -> None:         # tell it to decline once
        self._fail_next = True

    def charge(self, booking_id: str, amount_minor: int) -> "PaymentResult":
        self.charges.append(booking_id)
        if self._fail_next:
            self._fail_next = False
            return PaymentResult(False, "DECLINED")
        self.balance_minor -= amount_minor      # real behaviour, so the test
        return PaymentResult(True, f"TXN-{len(self.charges)}")  # can assert money


@pytest.fixture
def booking():
    """Hands back the doubles too: a fixture returning only the service forces
    every test to reach inside it to assert."""
    repo, gateway = InMemoryBookingRepository(), FakePaymentGateway()
    service = BookingService(repo, gateway, ids=SequentialIdGenerator("BKG"),
                             clock=lambda: NOON)  # a zero-arg callable IS the Clock
    return service, repo, gateway


def test_one_seat_yields_exactly_one_booking(booking):   # THE INVARIANT
    service, repo, gateway = booking
    service.book("SHOW-7", "4C", "alice", PRICE)
    with pytest.raises(SeatUnavailable):
        service.book("SHOW-7", "4C", "bob", PRICE)
    assert repo.count_for("4C") == 1
    assert len(gateway.charges) == 1        # bob never reached the gateway


# threading.Barrier(n) is the latch: nobody passes wait() until the nth thread
# arrives, so the concurrency test ports over directly. The GIL does not save
# you -- a seat claim is a read-modify-write across several bytecodes.
#
# And why a fake class rather than monkeypatch or unittest.mock.patch?
#     monkeypatch.setattr("booking.service.datetime", FrozenDatetime)
# That string is an import path, not a behaviour: it holds until someone moves
# the import, and then the patch silently stops patching while the test still
# goes green.
#include <cassert>
#include <chrono>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct PaymentResult { bool ok; std::string reason; };

class PaymentGateway {
public:
    virtual ~PaymentGateway() = default;
    virtual PaymentResult charge(const std::string& bookingId, long long minor) = 0;
};

// The fake derives from the interface, so it needs nothing but a compiler.
class FakePaymentGateway : public PaymentGateway {
public:
    PaymentResult charge(const std::string& bookingId, long long minor) override {
        charged_.push_back(bookingId);                  // the spy half
        if (failNext_) { failNext_ = false; return {false, "DECLINED"}; }
        balanceMinor_ -= minor;                         // the fake half
        return {true, "TXN"};
    }
    void failNextCharge() noexcept { failNext_ = true; }
    long long balanceMinor() const noexcept { return balanceMinor_; }
    std::size_t chargeCount() const noexcept { return charged_.size(); }

private:
    std::vector<std::string> charged_;
    long long balanceMinor_ = 500'000;
    bool failNext_ = false;
};

// The cheapest Clock seam there is: the test hands over a lambda returning a
// constant, production hands over system_clock::now.
using Clock = std::function<std::chrono::system_clock::time_point()>;

// No framework wired up and no time to wire one? A few asserts in main is a
// legitimate answer under time pressure -- runnable, loud, and it doubles as
// the demo. It stops at the first failure and will not name the case that died,
// so print a labelled expected-versus-actual line before each assert.
int main() {
    auto repo = std::make_shared<InMemoryBookingRepository>();
    auto gateway = std::make_shared<FakePaymentGateway>();
    const auto noon = std::chrono::sys_days{std::chrono::March / 14 / 2026}
                    + std::chrono::hours{12};
    BookingService svc(repo, gateway, std::make_shared<SequentialIdGenerator>("BKG"),
                       [noon] { return noon; });       // the injected Clock

    svc.book("SHOW-7", "4C", "alice", 25000);
    bool rejected = false;                             // THE INVARIANT
    try { svc.book("SHOW-7", "4C", "bob", 25000); }
    catch (const SeatUnavailable&) { rejected = true; }
    std::cout << "[1] double claim   expected=rejected  actual="
              << (rejected ? "rejected" : "ACCEPTED") << "\n";
    assert(rejected && repo->countFor("4C") == 1);
    assert(gateway->chargeCount() == 1);     // bob never reached the gateway

    gateway->failNextCharge();               // the rejection path, same shape
    try { svc.book("SHOW-7", "5C", "carol", 25000); assert(false); }
    catch (const PaymentFailed&) {}
    std::cout << "[2] declined card  expected=475000   actual="
              << gateway->balanceMinor() << "\n";
    assert(gateway->balanceMinor() == 475'000 && repo->countFor("5C") == 0);
}

What not to test, and the one test never to skip

What not to test. The suite that scores zero is fourteen tests that could only fail if you broke a line you did not write. Skip getters, setters and toString, since asserting that getSeat() returns the seat you passed the constructor tests the compiler. Skip the language and its library – HashMap works, BigDecimal rounds how its docs say – and skip third-party code too, because a test that calls a real gateway is not a unit test but an outage waiting for a network blip. And skip your own private methods: reach the logic through the public method that calls it, or the test must be rewritten the moment you rename the helper. A private method that is genuinely hard to reach that way wants to be its own class.

The one test that catches the most bugs in LLD problems is always the same shape: the invariant or round-trip test. Serialise then deserialise and compare to the original. Credit then debit and assert the balance returned. Split an expense three ways and assert the shares sum to the total, to the paisa. Each runs through your constructors, your equality, your money handling and your rollback path in one pass, which is why one of them finds more defects than a page of targeted tests – and why it is the only kind that checks what the problem is about rather than what your code happens to do.

Time and randomness are one bug in two hats, a dependency the class reaches for instead of receiving, and the fix is the same twice. Pass a Clock and hand it Clock.fixed(...) in tests, so the 22:00 branch is a constructor argument away instead of unreachable. Pass a Random built with a fixed seed, so a shuffled deck is the same shuffled deck every run and the failure your interviewer saw is one you can reproduce. A test whose result depends on when it runs is not a test, it is a scheduled outage.


Fakes vs mocks vs stubs vs spies

Candidates say “mocks” for all four, and interviewers who care about testing hear it. Each leaves the test asserting on a different thing, and that choice decides whether the test survives your next refactor:

Double What it is Asserts on Tell
Stub Returns canned answers; holds no expectations and makes no assertions The system under test’s own output It exists only to stop the real collaborator being called
Fake A real working implementation taking a shortcut – in-memory repository, gateway with a pretend balance Final state, plus the output You could point the running app at it and the app would work
Mock Pre-programmed with the calls it expects, and fails the test itself when they do not arrive The interactions The assertion lives inside the double – verify(...)
Spy Records the calls it received so the test can inspect them afterwards Recorded interactions, after the fact A real object with a notebook; the assertion is in the test

Recommendation: hand-write fakes. A fake lets you assert on behaviour – the seat is held once, the balance is 475000 – and behaviour is what the requirement states, so the test survives a change in how the class achieves it. A mock asserts on interactions, which encodes your current call sequence as a requirement: split charge into authorize plus capture, a perfectly good refactor, and a mock-based suite goes red everywhere while the system stays correct. A suite that punishes you for improving the design is backwards in a round graded on design. The blunter reason: the sandbox has no Mockito on the classpath, while class FakePaymentGateway implements PaymentGateway costs fifteen lines and hands you the wiring your demo needs anyway.

The honest caveat is that the fake above is part spy, because it counts charges. Reach for a call count only when the behaviour leaves no state to check: “the losing thread was never charged” has none, since the balance reads the same either way. Assert on state when state exists; fall back to calls when it does not.


When to Write the Test vs When to Just Say It

Write the test when Say it out loud instead when
The requirement names an invariant – no double booking, money conserved, stock never negative The method is a getter, a toString, or a one-line delegation with no rule in it
The branch is unreachable from the demo – a declined card, a full lot, an expired token The collaborator is a third-party library doing exactly what its docs say
The problem is concurrent and the claim is “exactly one wins” The test would need a real clock, a real network, or a sleep to pass
You refactored after minute 60 and need something to catch what you broke You are under five minutes and the demo does not run yet – fix the demo
The interviewer asked for tests, or asked “how do you know this works?” It is a private helper, already covered through the public API

The characteristic failure mode comes in two mirrored forms. One candidate submits fourteen tests, all asserting that constructors assign fields, none of which would notice seat 4C sold twice. The other spends twenty-five minutes on a tidy harness and submits a system whose main throws on line three. The target between them is narrow: a demo that runs and asserts, the two or three tests that pin the invariants, and a spoken list of what came next.


Interview Questions

  1. “How would you test this?” – A strong answer names cases, not tooling: the invariant, that one seat cannot produce two bookings, asserted through the repository rather than the return value; the rejection path, where a declined payment must release the seat and move no money, using a fake gateway you can tell to decline; and the concurrent claim, twenty threads on a latch with exactly one winner. Then point at the constructor and say why you can test it – clock, id generator and gateway all injected. “JUnit and Mockito” names your tools and says nothing about your design.

  2. “Fakes or mocks?” – Fakes, because a fake lets the test assert on behaviour while a mock forces it to assert on interactions. Splitting charge into authorize and capture leaves behaviour identical, so a fake-based test still passes where a mock-based one fails on a call sequence nobody required. Mocks earn their place when there is no observable behaviour to check – that an audit event was emitted, that a retry happened three times.

  3. “How do you test code that calls now() and nextInt()?” – Stop calling them and start receiving them: a Clock and a Random as constructor parameters, Clock.fixed(...) and new Random(42) in tests, Clock.systemUTC() and a fresh Random in production. The 22:00 discount then becomes two ordinary cases instead of a line you can only exercise after dinner. Patching the import works, but it binds the test to an import path rather than to behaviour, so it keeps passing after it has quietly stopped patching anything.

  4. “How do you write a concurrency test that isn’t flaky?” – Make the interleaving deterministic instead of probable. Spawn the threads, block every one on a CountDownLatch until all N have arrived, release them with a single countDown, then join with a timeout so a deadlock fails fast instead of hanging the suite. Assert on totals – one win, N-1 rejections, one row in the repository – never on which thread won, and validate the test by deleting the lock: if it does not go red, it was never testing the lock.

  5. “You’re out of time. What do you cut?” – Bottom first, in this order: the per-strategy unit tests, because the interviewer can see a pure function is a pure function; then the edge cases that merely echo the happy path; then the concurrency test, if you can state the interleaving it would have forced. The runnable demo and the invariant assertion never get cut, since together they are the only evidence the system does what the problem asked. And announce the cut – “no test on the refund path, that’s the first thing I’d add” reads as judgment, while silence reads as an oversight.


See It in Action

  • Movie Ticket Booking – the double-booked seat is the canonical invariant, and the latch test the canonical proof
  • Splitwise – shares must sum to the total to the paisa, the round-trip test that finds every rounding bug
  • Inventory Management – stock never negative, under concurrent reservations against the last unit
  • Circuit Breaker – untestable without an injected clock, since every state transition is defined by a timeout