Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 29 ยท Real-world projects

Project: Testing a Shopping Cart with Mocks

Test a shopping cart service that depends on a product catalog: hand-rolled fakes and spies, nested test groups, tags for slow tests and selecting runs.

Most real classes do not live alone. A CartService asks a catalog for product prices; an OrderService talks to a payment gateway; a report builder reads a repository. To test such a class in isolation, you give it test doubles in place of the real collaborators. In this project you test a shopping cart service that depends on a product catalog, using doubles you write yourself: no mocking library, nothing hidden.

Writing them by hand once is the best way to understand what Mockito and similar libraries automate (see Mocks and Spies with Mockito). You will also organize the tests with @Nested groups and @Tag, then run only the fast tests, the way a CI pipeline does. Everything below runs on the real JUnit 6 API on our Java runner.

The design under test

Who talks to whom

CartService The class under test.
ProductCatalog Interface to find a product by SKU.
Test doubles A fake catalog and a slow catalog.

The service only knows the interface, so tests can swap the catalog.

1 / 2

The rules of the cart:

  • add(sku, quantity) puts items in the cart. The quantity must be positive, and the SKU must exist in the catalog.
  • Adding the same SKU twice merges into one line.
  • totalCents() sums price times quantity for each line. A line with 10 or more units gets a 10% bulk discount.
  • remove(sku) removes a whole line.

The only dependency is a small interface. Anything that can answer "which product has this SKU?" will do: a database, a web service, or a map in a test.

Java
interface ProductCatalog {
    Optional<Product> find(String sku);
}

The doubles

We need two test doubles. The fake is a working catalog backed by a map. It also counts lookups, which makes it a spy as well, so we can check that the cart does not ask for the same product again and again for no reason. The slow catalog simulates a remote service by pausing for a moment on each lookup; it exists to show tagging.

Writing the test class

Study the structure before you run it.

  • The outer class creates a fresh FakeCatalog and CartService in @BeforeEach. JUnit builds a new instance of the test class for each test, so no cart leaks from one test to the next.
  • @Nested classes are inner (non-static) classes. Their @BeforeEach runs after the outer one, so WhenHoldingItems starts from the same fresh cart and then adds items.
  • The slow test is tagged @Tag("slow"). Tags do not change how a test runs; they only give the launcher something to filter on.
  • A @DisplayName on each nested group gives the report readable headings.
Java Cart service tests with a fake catalog and nested groups

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.

The third group of lines is the interesting one: a pipeline can run the fast tests on every commit and the slow ones on a schedule. In a real build you do not write the request() helper; you set the same filter in the build file (excludedGroups for Surefire, excludeTags for Gradle; see Running Tests with Maven and Gradle).

What the tests are careful about

  • Behavior through the public API. The tests ask totalCents() and quantityOf(...); they never read the private map. The cart could switch to a TreeMap tomorrow and no test would care.
  • Boundaries of the bulk rule. Nine pens get no discount and ten do. These two tests surround the >= 10 condition, so a typo like > 10 or >= 9 fails one of them.
  • Failure leaves the cart unchanged. Adding an unknown product or a zero quantity must not create a line. Both tests assert isEmpty() afterwards.
  • The spy test is deliberate and loose. totalAsksTheCatalogOncePerLine states a real performance promise (one lookup per line, not per unit). It compares a difference, so it does not break when add also performs lookups. It would be over-specification to also assert the order of lookups.
  • Slow things are isolated. The slow catalog has its own tag, so a quick local run never waits for it.

If you find yourself writing a spy that checks every interaction, pause. Tests that verify how the code works, rather than what it achieves, break on harmless refactoring. Keep interaction checks for the cases where the interaction is the behavior, such as "an email was sent".

Mocking an interface that throws

Not every double returns data. Often you need a collaborator that fails, to prove your code handles errors. A tiny anonymous class does the job: it implements the interface and throws. The next example tests a CartService whose catalog is unavailable, and checks that the cart does not end up in a half-updated state.

Java A catalog that fails

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.

Because ProductCatalog has a single method, a lambda is the shortest possible double. The int[] calls array is a standard trick for letting a lambda change a counter. For richer behavior (different answers on successive calls, verifying argument values), you graduate to Mockito, which wraps exactly these ideas in when(...).thenReturn(...) and verify(...).

Extending the project

  • Add a coupon collaborator (CouponService.discountFor(code)) and test an expired code with a controllable clock (see Flaky Tests and Common Mistakes).
  • Add a repository that persists carts, and write one set of tests that runs against both the in-memory fake and a real database later. That shared set is called a contract test.
  • Convert the discount boundaries to a table with @CsvSource (see Parameterized and Dynamic Tests).
  • Redo this suite in Mockito and compare how much code you save, and what readability you give up.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does CartService depend on the ProductCatalog interface instead of a concrete database class?

    Depending on an interface is the seam that makes substitution possible. Production passes a real catalog, tests pass a double.
  2. 2. What does @Tag("slow") change when a test runs by itself?

    Tags are metadata. Filters such as TagFilter.excludeTags, Surefire groups or Gradle includeTags use them to select tests.
  3. 3. Why are the bulk discount tests written for nine and for ten units?

    Boundary tests sit on each side of the condition. A change to > 10 or >= 9 breaks one of them.
  4. 4. Which is a sign of an over-specified spy test?

    Interaction checks should be limited to cases where the interaction is the behavior. Otherwise they pin down implementation details.
  5. 5. In a @Nested class, in what order do the @BeforeEach methods run?

    Setup flows from outside in. The nested group starts from the outer fixture and then adds its own.

Summary

  • Test a class with collaborators by giving it doubles behind an interface: a fake for working behavior, a spy to count or record, a lambda to stub or to fail.
  • Hand-written doubles are plain Java; mocking libraries only automate the same ideas.
  • @Nested classes group tests by scenario, with setup running from the outer class inwards, and @DisplayName labels them in the report.
  • @Tag marks categories such as slow; filters on tags select what a run includes. In real builds this is configured in Surefire groups or Gradle includeTags and excludeTags.
  • Assert behavior (totals, quantities, no change after failure), pin boundaries, and keep interaction checks for cases where the interaction is the point.
  • The examples ran on the real JUnit 6 API; the request() helper stands in for what your build tool configures.

Next: Project: Build a Mini Test Framework, where you discover how annotations and reflection let JUnit find and run your tests.