Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: Order Service Tests

Build and test an order checkout service with an inventory, a payment gateway, a repository and a mailer: stubs for inputs, verified effects, failure paths and compensation.

In this project you test a realistic service: checkout. It reserves stock, charges a card, saves the order and sends a confirmation email. It also has to behave when things go wrong: no stock, a declined card, a payment system that throws. This is the typical shape of a Mockito test suite in a business application.

You will write the service and a test suite in plain Java that runs in the browser with the labelled Mini stand-in (Mockito itself is not available on this site), and then see how the same tests look in real Mockito and JUnit 5.

The design

flowchart LR
  C["CheckoutService"] --> I["Inventory"]
  C --> P["PaymentGateway"]
  C --> R["OrderRepository"]
  C --> M["Mailer"]

One class under test, four collaborators, all behind interfaces and injected through the constructor.

Rules of the service:

  1. If the item is not in stock, return OUT_OF_STOCK and do nothing else.
  2. Reserve the stock, then charge the card.
  3. If the charge is declined, release the stock and return DECLINED. No order is saved, no email is sent.
  4. If the payment gateway throws an exception, release the stock too and let the failure be reported as PAYMENT_ERROR.
  5. On success: save the order as PAID, send an email, return PAID.

Which doubles fit? The inventory and the gateway answer questions (stub them). The repository and the mailer are outgoing effects (verify them), see Fakes, stubs and mocks: choosing.

The code and the tests

The program contains the service, a tiny test(name, body) helper, and five tests. Run it and read the report.

Java Checkout service with five tests

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

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

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

Four tests pass and the last one fails on purpose, so you can see what a Mockito verification failure looks like: it names the wanted count, the actual count and the call.

Observe how each test names its scenario, stubs only what that scenario needs, asserts the visible result, and then verifies only the effects that matter for that path. The "does nothing else" checks (verify(..., 0)) are about money and email, the things that must not happen.

The same tests in real Mockito

Java
@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {

    @Mock Inventory inventory;
    @Mock PaymentGateway gateway;
    @Mock OrderRepository orders;
    @Mock Mailer mailer;
    @InjectMocks CheckoutService service;

    @Test
    void paidOrderIsSavedAndConfirmed() {
        when(inventory.reserve("book")).thenReturn(true);
        when(gateway.charge("4111", 1500)).thenReturn(true);

        String result = service.checkout("o1", "book", "4111", 1500, "[email protected]");

        assertEquals("PAID", result);
        verify(orders).save("o1", "PAID");
        verify(mailer).send("[email protected]", "Thanks for order o1");
        verify(inventory, never()).release(any());
    }

    @Test
    void gatewayExceptionReleasesStock() {
        when(inventory.reserve("book")).thenReturn(true);
        when(gateway.charge(any(), anyInt())).thenThrow(new IllegalStateException("gateway down"));

        assertEquals("PAYMENT_ERROR", service.checkout("o4", "book", "4111", 1500, "[email protected]"));

        verify(inventory).release("book");
        verifyNoInteractions(orders, mailer);
    }
}

Differences from the stand-in: annotations create the mocks, matchers (any(), anyInt()) replace exact arguments, verifyNoInteractions(orders, mailer) expresses the "nothing else" rule in one line, and strict stubs would flag any stub that a test does not use.

Extension ideas

  1. Add a discount collaborator and a test that the charged amount is reduced; capture the amount with an ArgumentCaptor.
  2. Add idempotency: if orders already contains the order id, return DUPLICATE without charging. A fake repository suits this better than a mock.
  3. Replace RuntimeException with a custom PaymentException and test the message.
  4. Add a timeout: treat a slow gateway as an error (needs a Clock or an executor seam).
  5. Use InOrder to verify that the stock is reserved before the card is charged, and released after a failure (an ordering rule that matters).

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. In the checkout tests, why are inventory.reserve and gateway.charge stubbed but not verified?

    Stub inputs, verify outgoing effects. The returned status depends on the stubbed answers.
  2. 2. Which checks guard the rule 'a declined card must not create an order or send an email'?

    Negative verifications express that a side effect must not happen.
  3. 3. Why does each test call setUp() to build new mocks?

    Fresh mocks per test keep tests independent; MockitoExtension does this for you.

Summary

  • A checkout service has input collaborators (stub) and output collaborators (verify).
  • Each test covers one scenario: happy path, no stock, decline, exception.
  • Failure paths must undo earlier steps (release the stock) and must not trigger later effects.
  • Use negative verifications for effects that must not happen; keep the rest asserted on results.
  • Fresh mocks per test keep scenarios independent.

Next: Project: notification dispatcher