Workbench / Volume 3 Exercises: The Backend
V3·54
Testing Backend Systems
Exercises for Volume 3, chapter 54: what tests are for and the shape of a suite; test doubles; unit tests with JUnit, AssertJ and Mockito; property-based and mutation testing; Spring test slices and context caching; repository tests with a real database and Testcontainers; API tests; WireMock; contract tests; architecture tests; end-to-end, system and performance tests; flaky tests; testing across languages; and a checklist for a Spring service. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. The tests run on JUnit 5 (Jupiter) through the JUnit Platform launcher, with PostgreSQL 16 for database tests, on JDK 21. Mockito, AssertJ, Testcontainers, WireMock, ArchUnit and PIT weren't available offline, so their exercises give expected behaviour, marked as such. Every quoted output is real, and five of them catch experienced developers:
- P1. Two tests sharing a static list passed in the usual order. Run with random method order (seed 31337), both failed, and the second test run alone failed too:
expected: <2> but was: <1>. - P1. A breakfast-cutoff test using
LocalTime.now()passed with the JVM in UTC (07:43) and failed in Asia/Kolkata (13:13) at the same instant. With an injectedClock, both runs agreed. - P2. 200
@RepeatedTests incrementing a static counter under JUnit's parallel execution ended at 134, not 200, and every test reported success. - P3. Two database tests rolled back after each test, so the table was empty both times. But the second insert got id 2, not 1: sequences don't roll back.
- P4. A property ("adding an item never lowers the total") failed after 29 random cases. Shrinking found ₹499.99 plus 1 paisa: the total fell from 52,499 to 47,250 paise, because the ₹50 discount kicks in at ₹500. A grid check found 510 violating pairs.
The chapter's lab already covered these, and the exercises build on them rather than repeat them:
- coverage against mutation testing: a weak suite with full line coverage killed 1 of 6 mutants, and the strong suite killed all 6;
- a bill-splitting property that example tests missed (shrunk to 1 paisa among 2);
sleep(50)flaking 51% of 200 runs, against awaiting the result with 0 failures;- costs: unit tests at 0.087 ms each, database tests at 0.93 ms, an application start at 3–4 s.
Coverage map.
| Chapter component | Exercises |
|---|---|
| what tests are for; the shape of a suite | T1 |
| test doubles | T2, P5 |
| JUnit, AssertJ, Mockito | T2, P1, P5 |
| property-based testing | T3, P4 |
| mutation testing | T3, P4 |
| Spring slices; context caching | T4, P6 |
| repository tests; Testcontainers | T5, P3 |
| API tests; WireMock | T6, P7 |
| contract tests | T6, P8 |
| architecture tests | T7, P9 |
| end-to-end, system, performance tests | T8 |
| flaky tests | T8, P1, P2 |
| other languages; the checklist | T9 |
Theory
T1. What tests are for, and the shape of a suite
- Name the jobs tests do: - catch regressions; - document behaviour; - enable refactoring; - drive design (TDD); - give confidence to deploy.
Why is "confidence to deploy on a Friday" the real measure, and why isn't line coverage (the lab: 100% lines, 1 of 6 mutants killed)?
2. The shape of a suite: the test pyramid (many unit tests, fewer integration tests, few end-to-end tests), the "testing trophy" (more integration), and "honeycomb" for microservices. The lab measured 0.087 ms per unit test, 0.93 ms per database test, and 3–4 s to start the application. How should those costs shape TiffinBox's suite for the order service?
3. Decide the right level for each test:
- Money.add overflow;
- the discount rule;
- "placing an order inserts the order and an outbox row in one transaction";
- "the JSON field is totalPaise, not total_paise";
- "the payment client retries on 503 but not on 400";
- "a customer can't read another customer's order";
- "checkout p99 < 800 ms at 600 req/s".
T2. Test doubles, JUnit, AssertJ and Mockito
- Define dummies, stubs, spies, mocks and fakes (in-memory implementations:
InMemoryOrders, ch37's ports). When is a fake better than a mock (stateful collaborators, many interactions), and why does over-mocking make tests brittle ("verify every call" tests that break on refactors)? - JUnit 5 features:
-
@Test,@ParameterizedTestwith@CsvSourceand@MethodSource; -@Nested; -@DisplayName; -@BeforeEachagainst@BeforeAll; -@TempDir; -@Timeout; -@RepeatedTest; - extensions; - test instance lifecycle; -@TestMethodOrder(P1: random order exposed hidden coupling).
AssertJ's fluent assertions (assertThat(order.lines()).extracting(Line::dishId).containsExactly(…), assertThatThrownBy, soft assertions), and why good failure messages matter.
3. Mockito: when(...).thenReturn, verify (when interactions are the behaviour: "an SMS was sent once"), argument captors, @Mock against @MockitoBean in Spring tests (T4: a new bean definition per combination invalidates the context cache), and strict stubs. When should you not mock at all (types you don't own, value objects, the database)?
T3. Property-based and mutation testing
- Explain property-based testing (generators, properties, shrinking; jqwik for Java). The lab found a bill-splitting bug that example tests missed. P4 checked "adding an item never lowers the total" and found the counterexample ₹499.99 + 1 paisa (52,499 → 47,250 paise), and a grid check found 510 violating pairs. Is that a code bug or a business-rule bug? What should the team decide?
- Kinds of properties:
- invariants (shares sum to the total);
- round trips (
parse(format(x)) == x, JSON serialisation); - metamorphic relations (adding an item never lowers the total; sorting is idempotent); - model-based testing (compare an implementation with a simple model, for example a state machine against a table of allowed transitions); - oracles (an old implementation).
Write three properties for TiffinBox's order state machine. 3. Mutation testing (PIT): - mutants (changed conditionals, removed calls, changed returns); - killed against survived; - equivalent mutants; - the mutation score.
The lab: a weak suite with 100% line coverage killed 1 of 6 mutants. Where should mutation testing run (the domain core, incremental on changed code in CI), and what's a sensible target?
T4. Spring test slices and context caching
- The slices:
-
@WebMvcTest(controllers, advice, converters, security; no services); -@DataJpaTest(JPA, repositories, an embedded or real database, transactions rolled back); -@JsonTest; -@RestClientTest; -@SpringBootTest(the whole application, optionally with a real server:webEnvironment = RANDOM_PORT).
What does each load, and which bugs can each catch or miss?
2. Context caching: Spring caches application contexts by their configuration (classes, profiles, properties, @MockitoBeans, initializers). The lab measured 3–4 s per start. Explain what breaks the cache:
- a different @MockitoBean set;
- @DirtiesContext;
- different @TestPropertySource values;
- @ActiveProfiles variations.
How do you design a suite with very few contexts (a shared base class, mocks declared in one place, spring.test.context.cache.maxSize)?
3. Transactions in tests: @Transactional on a test rolls back after each test. What does that hide?
- code that only works inside a transaction;
- lazy loading that would fail in production;
- AFTER_COMMIT listeners that never fire (ch46);
- committed-data visibility to other threads.
When should a test commit for real (and clean up)?
T5. Repository tests with a real database, and Testcontainers
- Why test repositories against the real database instead of H2 or mocks?
- SQL dialect features (
ON CONFLICT,FOR UPDATE SKIP LOCKED,jsonb, row comparisons in keyset pagination); - constraints and their SQLSTATEs (ch49's P2); - transaction isolation behaviour; - time zones (ch49's P1); - performance characteristics (indexes). - Testcontainers:
@Testcontainerswith@Container static PostgreSQLContainer,@ServiceConnection(Spring Boot 3.1+), reusable containers, a singleton container started once per JVM, and Flyway migrations applied at startup (so tests also test migrations). How do you keep the database tests at the lab's ~1 ms per test? - P3: two tests rolled back after each test, yet the second insert got id 2. Explain why sequences don't roll back (they must be non-transactional, for concurrency), and list other things that leak between rolled-back tests (sequences,
NOTIFYs, changes made by other connections, advisory locks, data committed by code that opens its own transaction such asREQUIRES_NEW). How should tests identify their rows?
T6. API tests, WireMock and contract tests
- API tests:
-
MockMvc(andMockMvcTesterwith AssertJ) against@SpringBootTest(webEnvironment = RANDOM_PORT)withRestTestClient,WebTestClientor REST Assured; - what each exercises (filters and the servlet container in the latter); - testing problem details, security (ch50), ETags (ch45), pagination and idempotency keys. - WireMock for HTTP dependencies:
- stubs (
stubFor(post("/payments").willReturn(…))); - faults (withFault(CONNECTION_RESET_BY_PEER),withFixedDelay(2000)); - scenarios (stateful: fail twice, then succeed); - request verification (verify(2, postRequestedFor(…))); - recording.
How do you test ch52's retry and breaker behaviour with it? 3. Contract tests: - consumer-driven contracts (Pact: the consumer writes expectations, the provider verifies them); - provider-driven contracts (OpenAPI with Specmatic or Spring Cloud Contract); - event contracts (ch51's schemas).
Why do contract tests replace most cross-service end-to-end tests, and what do they not check (behaviour beyond the interface, performance)?
T7. Architecture tests
- ArchUnit rules for TiffinBox (ch37's hexagonal structure, ch44's packages):
- the domain doesn't depend on Spring, JPA or Jackson;
- controllers don't use repositories;
- adapters depend on ports, not the reverse;
- no cycles between modules;
-
@Transactionalonly on application services; - nojava.util.Date; - nonewFixedThreadPool(ch51); - noSystem.out.
Write three of them.
2. Spring Modulith's ApplicationModules.of(App.class).verify() (module boundaries, allowed dependencies, events between modules) and its documentation generation. How does it relate to ArchUnit?
3. When do architecture tests help (keeping a design from eroding as the team grows) and when do they hurt (rules nobody understands, frozen designs)? How do you introduce them into an existing codebase with violations (FreezingArchRule)?
T8. End-to-end, performance and flaky tests
- End-to-end and system tests: a few critical journeys (sign in, browse, order, pay, track) against a deployed environment, synthetic monitoring in production, and test data management. Why do large E2E suites become slow, flaky and ignored, and what replaces most of them (T6's contracts, T4's API tests)?
- Performance tests: - load, stress, soak and spike tests; - realistic workloads (ch41's measurement rules, open against closed models); - tools (k6, Gatling, JMeter); - SLO-based pass/fail (p99 < 800 ms at 600 req/s); - running them on every merge or nightly; - why test environments lie (data size, caches, noisy neighbours).
- Flaky tests. Collect the causes from this chapter:
- the lab's
sleep(50)(51% failures); - P1's order dependence (both failed with seed 31337); - P1's time zone (passed in UTC, failed in IST); - P2's parallel shared state (134 of 200); - P3's sequences (id 2); - plus ports, network calls and randomness without seeds.
What's the process for flaky tests (detect by reruns, quarantine, fix within a deadline, never "retry until green")?
T9. Testing across languages, and the checklist for a Spring service
- Compare testing stacks:
- Python (pytest fixtures, parametrisation, Hypothesis for properties,
responsesandrespx,testcontainers-python); - JavaScript and TypeScript (Vitest or Jest, Supertest, MSW for HTTP, fast-check for properties, Playwright); - Go (testing, table-driven tests,httptest, fuzzing built in withgo test -fuzz,testcontainers-go); - .NET (xUnit,WebApplicationFactory, FsCheck, Testcontainers); - Rust (#[test],proptest,cargo-mutants).
Which ideas from this chapter appear everywhere? 2. Go's native fuzzing and Java's Jazzer: how fuzzing differs from property testing (coverage-guided input generation, finding crashes and panics), and where to fuzz in TiffinBox (parsers: cursors, webhooks, CSV imports). 3. Complete the chapter's checklist for a Spring service, in order of value, and apply it to the order service.
Programming exercises
P1. Order-dependent and time-dependent tests
- Write two JUnit tests that share a static list and pass in declaration order. Run them with
MethodOrderer.Randomand several seeds, and run one alone. - Write a breakfast-cutoff check using
LocalTime.now(), and a test that passes or fails depending on the JVM's zone. - Fix both: fresh state per test, and an injected
Clockfixed to an instant and zone.
P2. Parallel tests and shared state
Enable JUnit's parallel execution (junit.jupiter.execution.parallel.enabled=true) and run 200 @RepeatedTests that increment a static counter with a read-then-write. Report the final count and the test results. Then fix it three ways:
- no shared state;
- @ResourceLock("counter");
- @Execution(SAME_THREAD) for that class.
Explain which is right for tests that share a database.
P3. Database tests: rollback, sequences and real commits
Against PostgreSQL, write: 1. two rolled-back tests that each insert "the first order" and assert its id is 1 (show the second failing); 2. a repository test that uses returned ids and business keys instead; 3. a test of "order plus outbox row in one transaction" that commits for real, kills the transaction halfway (an exception after the first insert), and asserts neither row exists; 4. a cleanup strategy (truncate between tests) with timings.
P4. Properties, shrinking and mutation testing
- Write the property "adding an item never lowers the total" for the ₹50-off-at-₹500 rule, run it on random cases, shrink the counterexample, and count violations on a grid.
- Propose a rule change that makes the property hold, and write the property-based test for the new rule (jqwik, or a hand-written generator).
- Hand-write five mutants of the pricing function (a boundary, the discount amount, the GST rate, rounding, the quantity check), and show which a weak and a strong suite kill.
P5. Fakes, mocks and outcome-based tests
Test the PlaceOrder use case (ch37) two ways:
- with Mockito mocks for every port, verifying each call;
- with fakes (InMemoryOrders, FakePayments recording charges, FixedClock, RecordingOutbox), asserting outcomes.
Then refactor the use case (check stock with one batched query instead of a call per dish), and count which tests break. Keep verify only where the interaction is the behaviour.
P6. Spring slices and the context cache
Build a test suite for the order service with @WebMvcTest, @DataJpaTest (on Testcontainers), @RestClientTest and @SpringBootTest. Enable context-cache debug logging and count the contexts created. Then:
- introduce three test classes that each @MockitoBean a different bean, and count again;
- consolidate the mocks into one base class;
- measure the suite time before and after (expected if Spring Boot's test jars aren't available).
P7. HTTP dependencies with WireMock
Test the PaymentClient (ch48's P5, ch52's P2) with WireMock:
1. retries on 503 with the same idempotency key (a scenario: fail, fail, succeed);
2. no retry on 400;
3. read timeout with withFixedDelay;
4. connection resets;
5. problem-body decoding into typed exceptions;
6. the circuit breaker opening after repeated failures and recovering.
Assert request counts with verify.
P8. Contract tests between the order service and its consumers
Set up contract testing for:
- the web BFF consuming GET /orders/{id} (consumer-driven with Pact, or provider-driven with the OpenAPI document and Specmatic);
- the notification service consuming OrderPlaced events (JSON Schema plus example-based tests);
- a breaking change (renaming totalPaise to total), shown failing in the provider's build.
P9. Architecture tests for TiffinBox
Write ArchUnit rules (T7) for the order service:
- the domain is framework-free;
- controllers don't use repositories;
- no cycles between modules;
- @Transactional only in application services;
- no newFixedThreadPool;
- no java.util.Date;
- no System.out;
- HTTP clients not called from @Transactional methods (ch49's S3).
Freeze existing violations and show a new violation failing. Add ApplicationModules.verify() if using Spring Modulith.
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–54)
C1. The order service's test suite, rebuilt for speed and trust
Rebuild the order service's suite (ch44–53) using this chapter:
- domain unit tests with properties and boundary tables;
- PIT on the domain core;
- repository tests on a shared Testcontainers PostgreSQL (rollback by default; committed tests for after-commit and outbox behaviour);
- API tests for every endpoint and error (MockMvc plus a few RANDOM_PORT tests);
- WireMock client tests for payments and maps (timeouts, retries, breakers);
- consumer and provider contracts;
- architecture rules;
- random order and an injected Clock;
- at most 5 Spring contexts;
- a flaky-test quarantine job;
- a CI pipeline with stages and time budgets.
Report the suite time, the number of contexts, the mutation score and the flaky rate before and after.
Combines: every chapter from ch37 (the core) to ch53 (caching).
C2. Testing the event-driven flows
Test ch51's event backbone and ch52's resilience end to end within one service boundary: - the outbox relay publishes exactly what was committed (committed tests); - consumers are idempotent under redelivery (deliver the same event twice); - per-key ordering with version guards (shuffle events and assert the final state); - DLQ routing for poison messages; - pausing on an open breaker; - an Awaitility-based asynchronous assertion style (no sleeps); - a deterministic mode with an inline executor.
Combines: ch38's concurrency, ch49's persistence, ch51's messaging, ch52's resilience, and this chapter.
C3. A testing maturity review of another team's service
Review a service's tests against T9's checklist:
- the suite's shape and time;
- the number of contexts;
- the mutation score of the core;
- real-database coverage;
- contract coverage;
- flaky-test history;
- sleeps, now()s, static state, fixed ports;
- tests that roll back but should commit;
- security tests.
Deliver a scored report with the top five fixes.
Combines: everything in Volume 3.
What the chapter leaves out
Test-driven development in practice
TDD (red, green, refactor) works best for domain logic with clear inputs and outputs: pricing, state machines, parsers. Outside-in TDD starts from an API test and drives inwards with fakes. The value is the design pressure and the safety net; the cost is discipline. Many teams use it selectively for the core.
Testing data migrations
Migrations deserve their own tests: apply them to a snapshot of production-like data (anonymised), verify row counts and invariants, test the expand and contract steps separately, and time them (a migration that locks a large table for 10 minutes is an outage). Flyway's validate and running all migrations in every Testcontainers test catch syntax errors; data checks need dedicated tests.
Testing observability
Assert that important logs, metrics and traces exist: a test that a payment failure increments payments.failures, that the access log contains the route template (ch48's P2), and that the trace id propagates through the outbox (ch51). Micrometer's SimpleMeterRegistry and an in-memory span exporter make this practical.
Chaos and production testing
Canary releases, feature flags, shadow traffic (sending a copy of production requests to a new version and comparing responses) and chaos experiments (ch52) test in the only environment that's fully realistic. They complement pre-production tests, and need strong observability and fast rollback.
Test data builders and fixtures
Builders (anOrder().withLines(2).placedAt(T0).build()), the "object mother" pattern, and shared JSON fixtures keep tests readable and resilient to constructor changes. Avoid giant shared fixtures that every test depends on: changes ripple everywhere.
Senior exercises
S1. TiffinBox's testing standard
Write the standard: - the suite shape per service type; - the levels and what each must cover; - doubles policy (fakes for ports, real databases, WireMock at HTTP boundaries, no mocks of types you don't own); - properties and mutation testing for cores; - Spring context budget; - Testcontainers setup; - committed tests for transactional and async behaviour; - contracts for every interface; - architecture rules; - security and performance tests; - flaky-test policy; - CI stages and time budgets.
Tie each to an output.
S2. Review a test pull request
A PR adds:
- Thread.sleep(1000) before asserting an SMS was sent;
- a @SpringBootTest per test class with different @MockitoBeans;
- an H2 test of a repository method using ON CONFLICT DO NOTHING;
- assertEquals(1L, order.getId());
- verify(repo, times(1)).findById(7L); verifyNoMoreInteractions(repo) everywhere;
- a test of the order cutoff using LocalDateTime.now();
- @Transactional on a test of an AFTER_COMMIT cache eviction.
Write the review.
S3. Fix a slow, flaky pipeline
The order service's pipeline takes 28 minutes and fails 1 build in 5 for reasons that disappear on retry. Developers merge with "retry until green". Plan the investigation and the fixes, with measurements, and the cultural change.
S4. Teach "tests that lie" with five outputs
Prepare a 20-minute session using: - the lab's coverage against mutants (100% lines, 1 of 6 killed); - P1's random order (seed 31337) and time zone (UTC against IST); - P2's parallel counter (134 of 200, all passed); - P3's sequences (id 2); - P4's ₹499.99 cliff.
S5. Plan a testing programme
As the engineering-excellence lead, plan two quarters across 14 services:
- the testing standard (S1);
- shared test support in the starter (Testcontainers, base classes, a Clock bean, WireMock helpers, Awaitility);
- context consolidation;
- the flaky-test quarantine bot;
- contract testing rollout (a Pact broker or OpenAPI checks);
- PIT on cores;
- ArchUnit rules;
- load tests on main;
- the maturity review (C3) for every service;
- training (S4).
Give milestones, risks and metrics.