BE·54
Backend Testing
A testing strategy for backend services. Covers what to test at which level, test doubles, unit tests with JUnit, AssertJ and Mockito, property-based and mutation testing, Spring test slices and context caching, repository tests, API tests, Testcontainers for real databases and brokers, stubbing HTTP dependencies with WireMock, consumer-driven contract tests with Pact and Spring Cloud Contract, architecture tests, E2E and system tests, performance tests, and flaky-test hygiene. Compared with Go's testing package, Rust's test harness and proptest, .NET's xUnit and WebApplicationFactory, pytest and Hypothesis, ExUnit with the Ecto sandbox, and Zig's test blocks.
Start here: code that checks your code
What tests are for
A test is code that runs part of your program with known inputs and checks the result automatically. A good suite lets you change code with confidence: refactor, upgrade a library, fix a bug, and know within minutes that nothing else broke. It also documents what the code is supposed to do, in a form that can't go out of date. Tests come in sizes, and a healthy suite has many of the small, fast kind and fewer of the large, slow kind (the lab measured them: about 0.09 ms per unit test, 0.9 ms per database test, and seconds to start an application):
| Size | What runs | Speed | Catches |
|---|---|---|---|
| Unit | One class or function, dependencies replaced with test doubles | Microseconds to milliseconds | Logic errors, edge cases |
| Integration | Your code with a real database, broker or HTTP layer | Milliseconds to seconds | Mapping, SQL, configuration, serialisation |
| End-to-end / system | The deployed service (or several) through its public API | Seconds | Wiring, deployment, cross-service flows |
Code to test
/** Total in paise: lines × price, 5% GST, ₹50 off orders of ₹500 or more (before tax). */
public long total(Map<String, Integer> cart) {
if (cart.isEmpty()) throw new IllegalArgumentException("empty cart");
long subtotal = 0;
for (var e : cart.entrySet()) {
if (e.getValue() <= 0) throw new IllegalArgumentException("bad quantity for " + e.getKey());
long price = menu.priceOf(e.getKey()).orElseThrow(() -> new NoSuchElementException("not on menu: " + e.getKey()));
subtotal += price * e.getValue();
}
if (subtotal >= 50_000) subtotal -= 5_000;
return subtotal + Math.round(subtotal * 0.05);
}
Checkout receives a MenuRepository through its constructor (chapter 46), which is what makes it testable: a test can hand it a stand-in instead of a real database.
The tests
class CheckoutTest {
// a hand-written fake: a real, tiny implementation of the dependency
static class FakeMenu implements Pricing.MenuRepository {
final Map<String, Long> prices = new HashMap<>(Map.of("Masala dosa", 9_000L, "Filter coffee", 3_000L, "Thali", 18_000L));
int lookups = 0;
public Optional<Long> priceOf(String dish) { lookups++; return Optional.ofNullable(prices.get(dish)); }
}
FakeMenu menu; Pricing.Checkout checkout;
@BeforeEach void setUp() { menu = new FakeMenu(); checkout = new Pricing.Checkout(menu); } // fresh objects for every test
@Test @DisplayName("adds 5% GST to a small order")
void smallOrder() {
long total = checkout.total(Map.of("Masala dosa", 2, "Filter coffee", 1)); // arrange + act
assertEquals(21_000 + 1_050, total); // assert: ₹210 + ₹10.50 GST
}
@Test @DisplayName("takes ₹50 off orders of exactly ₹500")
void discountAtBoundary() { menu.prices.put("Special", 50_000L); assertEquals(47_250, checkout.total(Map.of("Special", 1))); }
@Test @DisplayName("no discount at ₹499.99 worth of food")
void justBelowBoundary() { menu.prices.put("Special", 49_999L); assertEquals(52_499, checkout.total(Map.of("Special", 1))); }
@Test void rejectsEmptyCart() {
var e = assertThrows(IllegalArgumentException.class, () -> checkout.total(Map.of()));
assertEquals("empty cart", e.getMessage());
}
@Test void rejectsUnknownDish() { assertThrows(NoSuchElementException.class, () -> checkout.total(Map.of("Pizza", 1))); }
@Test void rejectsZeroQuantity() { assertThrows(IllegalArgumentException.class, () -> checkout.total(Map.of("Thali", 0))); }
@Test void looksUpEachDishOnce() { checkout.total(Map.of("Thali", 3, "Filter coffee", 2)); assertEquals(2, menu.lookups); }
@TestFactory @DisplayName("GST on single items")
Stream<DynamicTest> gstTable() {
return Stream.of(new long[][]{{3_000, 3_150}, {9_000, 9_450}, {18_000, 18_900}, {1, 1}, {10, 11}})
.map(c -> DynamicTest.dynamicTest("₹" + c[0] / 100.0 + " → " + c[1] + " paise", () -> { menu.prices.put("X", c[0]); assertEquals(c[1], checkout.total(Map.of("X", 1))); }));
}
}
✔ rejectsEmptyCart()
✔ rejectsUnknownDish()
✔ no discount at ₹499.99 worth of food
✔ rejectsZeroQuantity()
✔ looksUpEachDishOnce()
✔ adds 5% GST to a small order
✔ ₹30.0 → 3150 paise
✔ ₹90.0 → 9450 paise
✔ ₹180.0 → 18900 paise
✔ ₹0.01 → 1 paise
✔ ₹0.1 → 11 paise
✔ takes ₹50 off orders of exactly ₹500
12 passed, 0 failed in 447 ms
The anatomy is the same in every language's test framework (pytest, Go's testing, xUnit, Jest/Vitest, Rust's #[test]):
@Testmarks a test method;@BeforeEachbuilds fresh objects for each test, so tests can't affect each other.- Each test follows arrange, act, assert: set up inputs, call the code, check the outcome with assertions (
assertEquals(expected, actual),assertThrows). - Tests target behaviour at the edges: exactly ₹500 and one paisa below it (boundaries are where bugs live), empty input, unknown dishes, zero quantities, and rounding of tiny amounts (
{10, 11}: 0.5 paise of GST rounds up). @TestFactorygenerates a table of cases from data; JUnit's@ParameterizedTestdoes the same declaratively.- Test doubles replace real dependencies: a fake (a working lightweight implementation, like
FakeMenu), a stub (returns canned answers), a mock (records calls so the test can verify them;looksUpEachDishOncechecks interactions the way Mockito'sverifywould). Prefer real objects and fakes; use mocks for interactions that matter, not to replicate the implementation.
The order of the output shows that JUnit doesn't promise to run tests in source order: each test must stand alone.
Beyond unit tests
For a Spring service, integration tests check what unit tests can't: that the SQL is right (against a real PostgreSQL, usually started by Testcontainers, rather than an in-memory imitation), that JSON looks the way clients expect (@WebMvcTest, @JsonTest), and that a @SpringBootTest application starts and answers. The lab shows two things code coverage hides: a suite can execute every line and still miss most bugs, and a test that waits with sleep fails half the time.
How deep to go in backend testing
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Write unit tests with JUnit and assertions; run them in the build |
| L2 | Use test doubles, parameterised tests, Spring test slices, Testcontainers and API tests |
| L3 | Explain test strategy (shape, contracts, doubles), mutation and property-based testing, context caching, and flakiness causes |
| L4 | Diagnose weak assertions, flaky tests, slow suites and false confidence from coverage |
| L5 | Design a service's test strategy and CI gates (contract tests, performance tests, quarantine) |
| L6 | Set testing standards and quality signals across many teams and services |
Strategy
What tests are for
Tests buy confidence to change code. They catch regressions, document behaviour, and drive design (code that's hard to test is usually poorly factored). They cost time to write, time to run, and maintenance when the code changes. A good suite maximises confidence per unit of cost, which means:
- Fast feedback: most tests run in seconds locally, and the full suite in minutes in CI.
- Realism where it matters: the bugs that hurt in backends live at boundaries (SQL that doesn't do what you think, serialisation, transactions, HTTP contracts, configuration), so those need tests against real or realistic dependencies.
- Testing behaviour, not implementation: assert on outcomes (responses, state, emitted events), not on which private methods were called. Over-mocked tests break on every refactor and pass when the system is broken.
- Determinism: no flaky tests. Control time, randomness, concurrency and external services.
The shape of a test suite
The classic test pyramid (Mike Cohn) says: many fast unit tests, fewer integration tests, very few end-to-end tests. For backend services, many teams find a "testing trophy" or "honeycomb" shape fits better, with the bulk of tests at the integration level, because a service's logic is often thin and its risk lives in its interactions with the database, broker and HTTP layer:
The point isn't the exact shape: each risk should be tested at the cheapest level that can actually catch it. A pricing rule is a unit test. "Our JPQL returns the right rows on PostgreSQL" is a repository test against PostgreSQL, not H2. "The order API returns Problem Details on validation errors" is a web slice or API test. "The billing service still understands our events" is a contract test.
Test doubles
Gerard Meszaros's vocabulary (xUnit Test Patterns), often all loosely called "mocks":
| Double | What it does | Example |
|---|---|---|
| Dummy | Passed but never used | A null-safe placeholder argument |
| Stub | Returns canned answers | given(prices.find("A")).willReturn(price) |
| Spy | Records calls (and may delegate to the real object) | Verify that an email was sent |
| Mock | Pre-programmed with expectations, verified | verify(gateway).charge(argThat(…)) |
| Fake | A working, simplified implementation | In-memory repository, FakeClock, local SMTP |
Guidance:
- Prefer fakes and real objects over mocks for things you own: an in-memory
OrderRepositoryfake exercises real behaviour and survives refactoring. - Mock at architectural boundaries you don't own or that are expensive (payment gateways, email, external APIs). For HTTP dependencies, prefer WireMock-level stubs (real HTTP) over mocking your client class, so serialisation and error handling are tested too.
- Don't mock types you don't own (JDBC,
RestClientinternals, Kafka consumers). Wrap them behind your own interface, or test against the real thing. - Inject time (
Clock, chapter 37) and randomness (seeded generators, ID suppliers), so tests are deterministic.
Unit level
Unit tests: JUnit, AssertJ and Mockito
class PricingTest {
private final Clock clock = Clock.fixed(Instant.parse("2026-10-24T10:00:00Z"), ZoneOffset.UTC);
@Test
void appliesBulkDiscountAboveTenUnits() {
var cart = Cart.of(line("SKU-1", 12, "10.00"));
var quote = Pricing.quote(cart, PriceList.standard(), LocalDate.now(clock));
assertThat(quote.discount()).isEqualByComparingTo("12.00"); // BigDecimal: compare value, not scale
assertThat(quote.total()).isEqualByComparingTo("108.00");
}
@ParameterizedTest(name = "{0} units → {1}% discount")
@CsvSource({ "1, 0", "9, 0", "10, 10", "50, 15" })
void discountTiers(int qty, int expectedPercent) {
assertThat(Discounts.percentFor(qty)).isEqualTo(expectedPercent);
}
@Test
void rejectsNegativeQuantities() {
assertThatThrownBy(() -> Cart.of(line("SKU-1", -1, "10.00")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("quantity");
}
}
@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {
@Mock PaymentGateway payments; // boundary we don't own
@Mock OrderEventsPublisher events;
final InMemoryOrderRepository orders = new InMemoryOrderRepository(); // a fake for what we own
@Test
void chargesAndPublishesOnSuccess() {
var service = new CheckoutService(orders, payments, events, Clock.systemUTC());
given(payments.charge(any(), anyString())).willReturn(new Receipt("r-1"));
var order = service.checkout(cart(), "idem-1");
assertThat(orders.findById(order.id())).get().extracting(Order::status).isEqualTo(Status.PAID);
then(events).should().publish(argThat(e -> e instanceof OrderPaid p && p.orderId().equals(order.id())));
}
}
- JUnit 5 (Jupiter), and JUnit 6 with Spring Boot 4:
@Test,@ParameterizedTest(@CsvSource,@MethodSource,@EnumSource),@Nestedfor grouping,@DisplayName, extensions (@ExtendWith),@Tagfor selecting suites, and parallel execution. - AssertJ: fluent, readable assertions with good failure messages (
assertThat(list).extracting(Order::id).containsExactly(…),usingRecursiveComparison()). - Mockito:
mock,when/given,verify/then, argument captors,@Mock/@InjectMocks. Mockito 5 uses the inline mock maker by default, which can mock final classes. On JDK 21+, Mockito's agent should be configured explicitly, because dynamic agent loading prints warnings and will be disallowed by default. - Test names should describe behaviour ("chargesAndPublishesOnSuccess"), and each test should follow Arrange–Act–Assert (given/when/then).
Property-based testing
Example-based tests check the cases you thought of. Property-based testing (QuickCheck, Haskell, 1999) states properties that must hold for all inputs, generates hundreds of random inputs, and shrinks any failure to a minimal counterexample:
// jqwik (JUnit platform engine)
@Property
void moneyAdditionIsCommutative(@ForAll("amounts") Money a, @ForAll("amounts") Money b) {
assertThat(a.plus(b)).isEqualTo(b.plus(a));
}
@Property
void serialisationRoundTrips(@ForAll("orders") Order order) {
assertThat(json.read(json.write(order), Order.class)).isEqualTo(order); // decode(encode(x)) == x
}
@Provide Arbitrary<Money> amounts() {
return Arbitraries.bigDecimals().between(BigDecimal.ZERO, new BigDecimal("1000000")).ofScale(2).map(Money::eur);
}
// proptest
proptest! {
#[test]
fn sort_is_idempotent_and_ordered(mut v in prop::collection::vec(any::<i64>(), 0..1000)) {
v.sort();
let once = v.clone();
v.sort();
prop_assert_eq!(&v, &once); // idempotent
prop_assert!(v.windows(2).all(|w| w[0] <= w[1])); // ordered
}
}
# Hypothesis
from hypothesis import given, strategies as st
@given(st.lists(st.integers()))
def test_reverse_twice_is_identity(xs):
assert list(reversed(list(reversed(xs)))) == xs
// Go native fuzzing (1.18+): coverage-guided input generation, with a seed corpus
func FuzzParseSKU(f *testing.F) {
f.Add("TSHIRT-RED-L")
f.Fuzz(func(t *testing.T, s string) {
sku, err := ParseSKU(s)
if err == nil && ParseSKUMust(sku.String()) != sku { // round-trip property
t.Errorf("round trip failed for %q", s)
}
})
}
// $ go test -fuzz=FuzzParseSKU
-- QuickCheck: the original
prop_reverseInvolutive :: [Int] -> Bool
prop_reverseInvolutive xs = reverse (reverse xs) == xs
Useful properties: round-trips (parse/print, serialise/deserialise), invariants (balances never negative, totals equal the sum of lines), idempotence, commutativity, oracle comparison (an optimised implementation agrees with a simple one), and stateful/model-based tests (random sequences of operations against a model). Property tests find edge cases humans don't think of: empty lists, Unicode, extremes, overflows (chapter 33).
Mutation testing
Code coverage tells you which lines ran, not whether tests would notice a bug. Mutation testing introduces small faults (mutants) into the code, such as flipping > to >=, removing a method call, or returning a constant. It runs the tests and reports surviving mutants: changes no test detected. PIT (pitest) for Java (with incremental analysis for CI), cargo-mutants (Rust), Stryker (JS/.NET), mutmut (Python) and go-mutesting. It's expensive, so run it on core domain modules or changed code rather than on everything for every commit.
Integration level
Spring test slices and context caching
Chapter 47 introduced the slices. Using them well:
@WebMvcTest(OrderController.class)
@Import(ApiExceptionHandler.class)
class OrderControllerTest {
@Autowired MockMvcTester mvc;
@MockitoBean OrderService orders;
@Test
void validationErrorsAreProblemDetails() {
assertThat(mvc.post().uri("/api/orders").contentType(MediaType.APPLICATION_JSON).content("""
{"customerId": "", "lines": []}
"""))
.hasStatus(HttpStatus.BAD_REQUEST)
.hasContentType(MediaType.APPLICATION_PROBLEM_JSON)
.bodyJson().extractingPath("$.errors[*].pointer").asArray().contains("/customerId", "/lines");
}
@Test
@WithMockUser(authorities = "SCOPE_orders:read") // spring-security-test
void requiresWriteScopeToCreate() {
assertThat(mvc.post().uri("/api/orders").with(csrf()).contentType(MediaType.APPLICATION_JSON).content(VALID))
.hasStatus(HttpStatus.FORBIDDEN);
}
}
Context caching: the Spring TestContext framework caches application contexts across test classes with the same configuration (the same slice, properties, @MockitoBean set, profiles and so on). A suite of 200 @SpringBootTest classes that all share one configuration starts Spring once. Every distinct combination of @MockitoBeans, @TestPropertySources or @ActiveProfiles creates another context, which is slow and memory-hungry. Practices:
- Standardise a few base test configurations (abstract base classes or meta-annotations).
- Avoid sprinkling unique
@MockitoBeans across@SpringBootTestclasses. - Use
@DirtiesContextsparingly, since it destroys the cached context. - Watch the logs or Spring's test context metrics for how many contexts start.
Repository tests with a real database
Don't test JPA queries against H2 when you run PostgreSQL in production. Dialect differences (JSON operators, ON CONFLICT, window functions, case sensitivity, locking behaviour, sequences, constraint names, transaction isolation) make H2 tests pass for queries that fail in production, and fail for valid PostgreSQL features. Use the real database in a container:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // don't swap in an embedded DB
@Testcontainers
class OrderRepositoryTest {
@Container
@ServiceConnection // Boot wires spring.datasource.* from the container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");
@Autowired OrderRepository orders;
@Autowired TestEntityManager em;
@Test
void keysetPaginationReturnsNextPageInOrder() {
IntStream.range(0, 30).forEach(i -> em.persist(OrderFixtures.paid("c-1", Instant.parse("2026-10-01T00:00:00Z").plusSeconds(i))));
em.flush(); em.clear(); // clear: next reads hit the DB, not the persistence context
var first = orders.findFirst10ByCustomerIdOrderByCreatedAtDescIdDesc("c-1", ScrollPosition.keyset());
var second = orders.findFirst10ByCustomerIdOrderByCreatedAtDescIdDesc("c-1", first.positionAt(first.size() - 1));
assertThat(second.getContent()).allSatisfy(o -> assertThat(o.getCreatedAt()).isBefore(first.getContent().getLast().getCreatedAt()));
}
@Test
void loadingOrdersWithLinesUsesOneQuery() { // guard against N+1 (chapter 49)
… // assert the statement count with datasource-proxy or Hibernate statistics
}
}
@DataJpaTesttests are transactional and rolled back after each test by default, which isolates tests cheaply. But it also means commit-time behaviour isn't exercised (deferred constraints,@TransactionalEventListener(AFTER_COMMIT), flush ordering at commit). Test those with@Transactional(propagation = NOT_SUPPORTED)or full integration tests, and clean up explicitly.- Flush and clear the persistence context before asserting, or you're testing Hibernate's first-level cache rather than the database.
- Apply real migrations (Flyway or Liquibase run in tests), so the schema under test is the production schema.
Testcontainers
Testcontainers starts real dependencies in Docker containers from tests: PostgreSQL, MySQL, Kafka, RabbitMQ, Redis, MongoDB, Elasticsearch, LocalStack (AWS services), Keycloak, MockServer, and any image. It has libraries for Java, Go, .NET, Python, Node, Rust and others.
// A shared base for integration tests: containers started ONCE per JVM (singleton pattern), Boot wired automatically
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Import(TestcontainersConfig.class)
abstract class IntegrationTest {}
@TestConfiguration(proxyBeanMethods = false)
class TestcontainersConfig {
@Bean @ServiceConnection
PostgreSQLContainer<?> postgres() { return new PostgreSQLContainer<>("postgres:17-alpine"); }
@Bean @ServiceConnection
KafkaContainer kafka() { return new KafkaContainer("apache/kafka-native:4.0.0"); }
@Bean @ServiceConnection(name = "redis")
GenericContainer<?> redis() { return new GenericContainer<>("valkey/valkey:8-alpine").withExposedPorts(6379); }
}
// The same configuration can run the app locally with real dependencies:
// TestApplication.main → SpringApplication.from(App::main).with(TestcontainersConfig.class).run(args)
Practices:
- Pin image versions to match production (
postgres:17.x), notlatest. - Reuse containers across tests (singleton containers or bean-defined containers with Spring's cached context), and optionally across runs locally (
testcontainers.reuse.enable=true). - Isolate test data: unique IDs per test, truncating tables between tests, or transactions rolled back. Don't depend on test order.
- CI needs Docker (or Testcontainers Cloud, or a remote Docker host). Startup costs seconds per container, which is paid once per suite.
- Boot's
@ServiceConnectionreplaces the older@DynamicPropertySourceboilerplate for supported containers.
API tests
API tests drive the running application over real HTTP, through serialisation, filters, security, exception handling and persistence:
class OrderApiIT extends IntegrationTest {
@Autowired RestTestClient client; // Boot 4 (or WebTestClient / TestRestTemplate / RestAssured)
@Test
void createThenFetchOrder() {
var location = client.post().uri("/api/orders")
.header("Idempotency-Key", UUID.randomUUID().toString())
.headers(h -> h.setBearerAuth(TestTokens.withScopes("orders:write", "orders:read")))
.contentType(MediaType.APPLICATION_JSON)
.body(Map.of("customerId", "c-1", "lines", List.of(Map.of("sku", "SKU-1", "qty", 2))))
.exchange()
.expectStatus().isCreated()
.returnResult(Void.class).getResponseHeaders().getLocation();
client.get().uri(location)
.headers(h -> h.setBearerAuth(TestTokens.withScopes("orders:read")))
.exchange()
.expectStatus().isOk()
.expectBody().jsonPath("$.status").isEqualTo("PENDING")
.jsonPath("$.lines.length()").isEqualTo(1);
}
@Test
void sameIdempotencyKeyReplaysTheFirstResponse() { … }
@Test
void publishesOrderPlacedEvent() { // assert on a REAL Kafka topic, eventually
… create order …
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertThat(testConsumer.received("orders.events.v1")).anySatisfy(e -> assertThat(e).isInstanceOf(OrderPlaced.class)));
}
}
Asynchronous assertions use Awaitility (poll until a condition holds, with a timeout), never Thread.sleep, which is both slow and flaky. For security in tests, mint real JWTs signed by a test key (a JWKS served by WireMock or a Keycloak container), or use Spring Security's jwt() request post-processors in MockMvc tests.
Stubbing HTTP dependencies: WireMock
For external HTTP services, WireMock (or MockServer) runs a real HTTP server with programmable stubs. Your actual client code (serialisation, timeouts, retries, error handling) is exercised:
@WireMockTest(httpPort = 0)
class PaymentsClientTest {
@Test
void retriesOn503ThenSucceeds(WireMockRuntimeInfo wm) {
stubFor(post("/v1/charges").inScenario("flaky")
.whenScenarioStateIs(STARTED).willReturn(serviceUnavailable()).willSetStateTo("recovered"));
stubFor(post("/v1/charges").inScenario("flaky")
.whenScenarioStateIs("recovered").willReturn(okJson("""{"id":"ch_1","status":"succeeded"}""")));
var client = PaymentsClient.create(wm.getHttpBaseUrl(), Duration.ofMillis(500));
assertThat(client.charge(req(), "idem-1").status()).isEqualTo("succeeded");
verify(2, postRequestedFor(urlEqualTo("/v1/charges")).withHeader("Idempotency-Key", equalTo("idem-1")));
}
@Test
void timesOutOnSlowResponses(WireMockRuntimeInfo wm) {
stubFor(post("/v1/charges").willReturn(ok().withFixedDelay(2_000)));
var client = PaymentsClient.create(wm.getHttpBaseUrl(), Duration.ofMillis(500));
assertThatThrownBy(() -> client.charge(req(), "idem-2")).isInstanceOf(PaymentsUnavailable.class);
}
}
Test the failure modes, not just the happy path: timeouts, 429 with Retry-After, 5xx, malformed bodies, connection resets (Fault.CONNECTION_RESET_BY_PEER), and slow responses. That's where resilience code (chapter 52) is verified. Toxiproxy injects network faults (latency, bandwidth limits, cut connections) between your app and real containers.
Contract tests
In microservices, who guarantees that the consumer's expectations match the provider's API? Separately mocked tests can both pass while the integration is broken: the consumer stubs a field the provider renamed. Contract tests close that gap:
- Consumer-driven contracts (Pact): the consumer's tests run against a Pact mock provider and record the interactions they rely on (requests and the subset of response fields they actually use) as a pact file. The pact is published to a Pact Broker. The provider's CI replays every consumer's pact against the real provider and fails if any expectation is broken.
can-i-deploychecks gate releases. Pact has libraries for JVM, JS, Go, Rust, .NET and Python, so it works across languages. - Spring Cloud Contract: provider-driven contracts written in Groovy/YAML/Kotlin DSLs. They generate provider-side tests and stub JARs (WireMock stubs) that consumers use in their tests.
- Schema-based checks: OpenAPI or Protobuf schema compatibility checks in CI (
oasdiff,buf breaking) and schema-registry compatibility for events (chapter 51). They're cheaper but weaker, since they check shapes, not semantics or which fields consumers actually use.
// Pact consumer test (orders-service consuming customers-service)
@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "customers-service")
class CustomersClientPactTest {
@Pact(consumer = "orders-service")
V4Pact customerExists(PactDslWithProvider builder) {
return builder.given("customer c-1 exists")
.uponReceiving("get customer c-1")
.path("/customers/c-1").method("GET")
.willRespondWith()
.status(200)
.body(new PactDslJsonBody().stringValue("id", "c-1").stringType("email").booleanType("active")) // only what we use
.toPact(V4Pact.class);
}
@Test
void readsCustomer(MockServer server) {
var c = new CustomersClient(server.getUrl()).get("c-1");
assertThat(c.active()).isNotNull();
}
}
// Provider side: @Provider("customers-service") + @PactBroker + @State("customer c-1 exists") setup methods,
// verifying every published consumer pact against the running provider.
Architecture tests
ArchUnit (Java) turns architecture rules into unit tests: layering, dependency direction, naming, and "no cycles between packages". Similar tools exist elsewhere: NetArchTest for .NET, go-arch-lint/depguard for Go, cargo-deny and module privacy for Rust, and Spring Modulith's ApplicationModules.verify() for module boundaries in a modular monolith.
@AnalyzeClasses(packages = "com.shop")
class ArchitectureTest {
@ArchTest static final ArchRule domainIsFrameworkFree =
noClasses().that().resideInAPackage("..domain..")
.should().dependOnClassesThat().resideInAnyPackage("org.springframework..", "jakarta.persistence..");
@ArchTest static final ArchRule controllersDontTouchRepositories =
noClasses().that().haveSimpleNameEndingWith("Controller")
.should().dependOnClassesThat().haveSimpleNameEndingWith("Repository");
@ArchTest static final ArchRule noCycles = slices().matching("com.shop.(*)..").should().beFreeOfCycles();
}
System level
End-to-end and system tests
E2E tests run against the deployed system (several services, real infrastructure, sometimes a UI), exercising critical user journeys: sign up, place an order, pay, see it in order history. They catch integration and configuration problems no other level sees, but they're slow, flaky, expensive to maintain and hard to debug. Keep them few and focused:
- Cover the top business-critical journeys only, and leave detail to lower levels.
- Run them against a production-like environment after deploying (staging, or ephemeral preview environments per PR, Part VIII), and as post-deploy smoke tests in production.
- Make them independent and idempotent: each test creates its own data (unique users), and nothing depends on order.
- Build in observability: capture trace IDs, logs and screenshots on failure.
- Tools: Playwright (UI + API, Vol. 2 ch. 26), REST Assured or Karate for API journeys, and k6 or Gatling scenarios that double as functional checks.
Synthetic monitoring (scheduled E2E checks against production) and canary analysis (chapter 31 of Vol. 2, Part IX) extend testing into production.
Performance tests
Performance is a requirement, so test it deliberately (Vol. 11 covers performance engineering in depth):
| Test type | Question | Shape |
|---|---|---|
| Load test | Does it meet SLOs at expected peak load? | Ramp to target RPS, hold |
| Stress test | Where does it break, and how (gracefully)? | Increase until failure |
| Soak / endurance | Leaks or degradation over hours? | Moderate load for a long time |
| Spike test | Does it survive sudden bursts (autoscaling, queues, load shedding)? | Sudden jumps |
| Capacity test | How many instances for X RPS? | Measure per-instance throughput at SLO |
// k6: an open-model load test with thresholds as pass/fail criteria
import http from "k6/http";
import { check } from "k6";
export const options = {
scenarios: {
checkout: { executor: "constant-arrival-rate", rate: 200, timeUnit: "1s", duration: "10m",
preAllocatedVUs: 100, maxVUs: 500 }, // fixed arrival RATE: avoids coordinated omission
},
thresholds: {
"http_req_duration{endpoint:create_order}": ["p(99)<400"],
http_req_failed: ["rate<0.001"],
},
};
export default function () {
const res = http.post(`${__ENV.BASE}/api/orders`, JSON.stringify(randomOrder()), {
headers: { "Content-Type": "application/json", "Idempotency-Key": crypto.randomUUID() },
tags: { endpoint: "create_order" },
});
check(res, { "201": (r) => r.status === 201 });
}
Key pitfalls:
- Coordinated omission: closed-model tools (N users looping) slow down when the system slows down, so they under-report tail latency. Use open-model, constant-arrival-rate load (k6
constant-arrival-rate, Gatling open injection, wrk2). - Unrealistic data: tiny databases, perfectly warm caches, one hot key. Use realistic data volumes and distributions.
- Testing the load generator: make sure the generator isn't the bottleneck.
- No baselines: track results over time and compare per release.
- Wrong environment: a laptop isn't production. Test on production-like infrastructure, and measure with the same observability stack.
Microbenchmarks (JMH, criterion, testing.B, BenchmarkDotNet, chapter 41) are for isolated code paths, and complement load tests rather than replacing them.
Flaky tests
A flaky test passes and fails without code changes. Flakiness destroys trust in the suite: developers start re-running failures and ignoring red builds. Common causes and cures:
| Cause | Cure |
|---|---|
Time (now(), time zones, DST, midnight) |
Inject a Clock; fix the time zone in tests (TZ=UTC); avoid asserting on wall-clock durations |
Asynchrony (Thread.sleep, polling too briefly) |
Awaitility with generous timeouts; deterministic executors in unit tests |
| Shared state and test order | Unique data per test, cleanup, no static mutable state; run in random order to expose it |
| Concurrency and parallel runs | Isolate resources (ports, DB schemas, topics) per test or worker |
| External services and networks | Testcontainers and WireMock instead of shared environments |
Unordered collections (HashMap order, Map.of) |
Assert with containsExactlyInAnyOrder, or sort |
| Resource limits in CI | Right-size CI runners; avoid fixed ports; check container startup timeouts |
Track flakiness (CI test analytics), quarantine flaky tests quickly with an owner and a deadline, and fix the root cause rather than adding retries. Test retries hide real race conditions, which may be production bugs.
Testing across languages
| Ecosystem | Unit and assertions | Integration | Notable |
|---|---|---|---|
| Java/Spring | JUnit 5/6, AssertJ, Mockito, jqwik, PIT | Spring test slices, Testcontainers, WireMock, Pact, Spring Cloud Contract, ArchUnit, Awaitility | Context caching; @ServiceConnection |
| Go | testing package: table-driven tests, t.Run subtests, t.Parallel(), testify (optional), built-in fuzzing and benchmarks |
net/http/httptest (an in-process server and recorder), testcontainers-go, go test -race |
Tests live next to the code (_test.go); -race in CI catches data races |
| Rust | #[test] in the same file (#[cfg(test)] mod tests, which can test private functions), integration tests in tests/, doc tests (examples in docs are compiled and run), #[tokio::test], proptest, insta (snapshot testing), mockall |
testcontainers-rs, axum's oneshot for in-process HTTP tests, sqlx::test (a fresh database per test) |
cargo nextest for fast, isolated parallel runs; the type system removes whole classes of tests |
| C#/.NET | xUnit, NUnit, MSTest; FluentAssertions/Shouldly; NSubstitute/Moq; FsCheck | WebApplicationFactory<T> (an in-memory test server for ASP.NET Core), Testcontainers for .NET, WireMock.Net, PactNet |
Very similar to Spring's slices + MockMvc |
| Python | pytest (fixtures with scopes, parametrisation, plugins), Hypothesis, unittest.mock | FastAPI TestClient/httpx, testcontainers-python, pytest-postgresql, respx/responses for HTTP |
Fixtures compose dependencies elegantly |
| Elixir | ExUnit (async: true runs test modules concurrently), doctests, StreamData (property-based) |
Ecto SQL Sandbox: each test gets its own transaction-wrapped DB connection, so database tests run concurrently and roll back; Mox (behaviour-based mocks); Phoenix ConnTest |
Concurrent DB tests are a standout feature |
| TypeScript/Node | Vitest, Jest, node:test; fast-check | Supertest, testcontainers-node, MSW (mock HTTP), Pact JS | — |
| Zig | test blocks next to the code, run by zig build test; std.testing.expect/expectEqual; std.testing.allocator fails the test on memory leaks |
— | Leak detection in every test that allocates |
| C/C++ | GoogleTest/GoogleMock, Catch2, doctest, Unity (C) | Sanitizers (ASan, UBSan, TSan) in test builds, fuzzing (libFuzzer, AFL++) | Sanitizer CI jobs catch memory bugs that tests alone miss |
// Go: table-driven tests + httptest. The idiom you'll see in almost every Go codebase
func TestCreateOrder(t *testing.T) {
tests := []struct {
name string
body string
wantStatus int
}{
{"valid", `{"customerId":"c-1","lines":[{"sku":"A","qty":1}]}`, http.StatusCreated},
{"empty lines", `{"customerId":"c-1","lines":[]}`, http.StatusUnprocessableEntity},
{"malformed", `{`, http.StatusBadRequest},
}
srv := NewServer(NewService(NewMemRepo(), fakePayments{}))
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader(tt.body))
rec := httptest.NewRecorder()
srv.routes().ServeHTTP(rec, req)
if rec.Code != tt.wantStatus {
t.Errorf("status = %d, want %d; body: %s", rec.Code, tt.wantStatus, rec.Body)
}
})
}
}
test "money addition does not overflow silently" {
const a = Money{ .minor = std.math.maxInt(i64) };
try std.testing.expectError(error.Overflow, a.add(Money{ .minor = 1 }));
}
test "order list frees everything" {
const gpa = std.testing.allocator; // the testing allocator reports leaks
var list: std.ArrayList(Order) = .empty; // Zig 0.15+: unmanaged list, allocator passed per call
defer list.deinit(gpa);
try list.append(gpa, .{ .id = 1 });
}
A testing checklist for a Spring service
- Unit tests for domain rules and pure logic, including property tests for invariants and round-trips.
- Web slice tests for request validation, error mapping (Problem Details), security rules and serialisation.
- Repository tests on the real database (Testcontainers) for custom queries, pagination and locking, with N+1 guards.
- Integration tests for each use case through HTTP, with real DB and broker containers and WireMock for third parties, including failure modes.
- Contract tests for every API and event consumed by other teams.
- Architecture tests for module boundaries.
- A few E2E smoke tests of critical journeys after each deploy.
- Load tests before major launches and on a regular schedule, with SLO thresholds.
- CI hygiene: fast feedback first (unit + slices), the integration suite in parallel, flaky tests quarantined and fixed, and coverage and mutation reports on core modules.
Lab: how good is a test suite?
JDK 21 with JUnit Jupiter 5.13, PostgreSQL 16, and the Spring Boot 4.1.1 OrdersApp from chapter 48. The code under test is Checkout.total from Start here.
Experiment 1: coverage versus mutation testing
Two suites for Checkout.total. The weak suite has five tests that together execute every line (a small order, a big order that triggers the discount, an empty cart, an unknown dish, a zero quantity) but only check that totals are positive or that something was thrown. The strong suite is Start here's twelve tests. Six mutants (small deliberate bugs, the way mutation-testing tools like PIT generate them) were compiled in turn, and both suites run against each:
mutant boundary (>= 50_000 → > 50_000) | weak suite: 5 passed, 0 failed | strong suite: 11 passed, 1 failed
mutant no-discount (subtract 0 instead of 5,000) | weak suite: 5 passed, 0 failed | strong suite: 11 passed, 1 failed
mutant gst-rate (0.05 → 0.06) | weak suite: 5 passed, 0 failed | strong suite: 6 passed, 6 failed
mutant truncate (Math.round → (long) cast) | weak suite: 5 passed, 0 failed | strong suite: 10 passed, 2 failed
mutant qty-check (<= 0 → < 0) | weak suite: 4 passed, 1 failed | strong suite: 11 passed, 1 failed
mutant extra-lookup (price looked up twice) | weak suite: 5 passed, 0 failed | strong suite: 11 passed, 1 failed
Both suites have 100% line coverage of total. The weak one killed 1 of 6 mutants; the strong one killed all 6. Coverage measures what ran, not what was checked: it's useful for finding untested code (0% is a fact; 100% is not a verdict) and harmful as a target, because the cheapest way to raise it is tests like the weak suite. Mutation testing measures whether tests would notice a change in behaviour. Run PIT (pitest-maven or the Gradle plugin) on core domain logic, not the whole codebase, since it runs the suite once per mutant.
Experiment 2: a property finds what examples missed
A bill-splitting function and the example tests someone wrote for it:
static long[] splitNaive(long total, int n) { long[] s = new long[n]; Arrays.fill(s, total / n); return s; }
example tests: split ₹300 among 3 → [10000, 10000, 10000], ₹100 among 2 → [5000, 5000] (both pass)
property, naive: failed on random case #1 (503799 paise among 11), shrunk to 1 paise among 2 → shares [0, 0] sum to 0
property 'shares add up to the total and differ by at most 1 paisa', fixed: held for 1,000 random cases
Instead of choosing inputs, a property-based test states something that must hold for all inputs ("the shares add up to the total, and no two differ by more than a paisa") and checks it against many random ones. The first random case failed, because integer division drops the remainder whenever the total doesn't divide evenly, which the hand-picked examples happened to avoid. Shrinking then searched for the simplest failing input (1 paisa between 2 people), which makes the bug obvious. The fixed version gives the remainder to the first few people and passed 1,000 random cases. Use jqwik (Java), Hypothesis (Python), fast-check (TypeScript), proptest (Rust) or Go's testing/quick and fuzzing; properties shine for money, parsers, serialisation round-trips (decode(encode(x)) == x) and anything with invariants.
Experiment 3: a flaky test
The code sends a receipt asynchronously, taking 30–70 ms. Two ways to test it, each run 200 times:
200 runs: sleep(50) then assert → 102 failures (51%) | await the result with a timeout → 0 failures
"Sleep, then check" encodes a guess about timing, which is wrong whenever the machine is busy (CI agents always are). Half the runs failed, though the code had no bug. Wait for the condition instead, with a generous timeout: future.get(2, SECONDS), Awaitility's await().atMost(…).until(…), or a latch. Other common causes of flakiness: shared state between tests (static fields, a shared database without rollback), test order, time and time zones (inject a Clock), random data without a fixed seed, ports already in use, and real network calls. Treat a flaky test as a bug: quarantine it so it doesn't train people to ignore red builds, then fix it.
Experiment 4: what each kind of test costs
unit tests: 1000 run, 0 failed, 0.087 ms per test
db tests: 100 run, 0 failed, 0.930 ms per test (real PostgreSQL, each test rolled back)
app start 3940 / 3316 / 3077 ms | 100 API calls against the running app ≈ 1.2 s (about 12 ms each, including starting curl)
A unit test is about 10× cheaper than a database test, which is about 10× cheaper than an HTTP call, and starting a Spring Boot application costs as much as tens of thousands of unit tests. Two consequences. Push logic into plain classes testable without Spring or a database, keeping integration tests for the integration itself. And never pay the startup cost twice: Spring's test framework caches application contexts between test classes with identical configuration, but every unique combination of @MockitoBean, @TestPropertySource, profiles or @DirtiesContext creates another context. A suite with 30 slightly different configurations starts the application 30 times, which is the usual reason a Spring test suite takes ten minutes. Rolling back each database test in a transaction (as here, or Spring's default for @Transactional tests) keeps tests independent without recreating the schema.
Try it yourself
- Run PIT on
Pricing(or write mutants by hand as here) and add tests until every mutant dies. Which mutants were hardest to kill? - Write a property for Start here's
total: adding an item never decreases the total. Does it hold across the ₹500 discount boundary? What does that tell you about the business rule? - Make experiment 3's test deterministic without any waiting by injecting the executor and passing
Runnable::runin the test. - Count how many application contexts your own Spring project's test suite creates (enable
logging.level.org.springframework.test.context.cache=debug), and reduce it.
Revision sheet: backend testing
Key ideas
- Purpose: fast, trustworthy feedback that lets you change code; executable documentation.
- Shape: many unit tests, fewer integration tests, few end-to-end tests (pyramid, or "trophy" with more integration for glue-heavy services); test behaviour through public APIs.
- Unit level: JUnit 5/6 (
@Test, lifecycle,@Nested,@ParameterizedTest, dynamic tests, extensions), AssertJ, test doubles (dummy, stub, fake, spy, mock) with Mockito used sparingly. - Beyond examples: property-based testing (jqwik) with shrinking; mutation testing (PIT) as a measure of assertion strength; coverage as a map of untested code, not a target.
- Integration: Spring test slices (
@WebMvcTest,@DataJpaTest,@JsonTest,@RestClientTest), context caching,@SpringBootTestwithRestTestClient; Testcontainers with@ServiceConnection; transactions rolled back per test. - Dependencies: WireMock for HTTP stubs; consumer-driven contract tests (Pact, Spring Cloud Contract) or OpenAPI-based checks (Specmatic); ArchUnit for architecture rules.
- System level: end-to-end tests of critical journeys, performance tests (Gatling, k6, JMeter) with SLO-based assertions, chaos and fault injection.
- Flakiness: timing, shared state, order, time, randomness, network; quarantine and fix.
- Elsewhere: pytest and Hypothesis, Go
testingwith table tests and fuzzing, xUnit/NUnit with Moq/NSubstitute, Jest/Vitest, Rust#[test]and proptest, ExUnit with StreamData.
Numbers to remember
- Lab: a suite with 100% line coverage killed 1 of 6 mutants (a stronger one killed 6); a property found a bill-splitting bug on the first random case; sleep-based waiting failed 51% of 200 runs; unit test 0.09 ms, database test 0.9 ms, Spring Boot start about 3 s.
Pitfalls
- Coverage targets driving assertion-free tests.
- Over-mocking (tests that mirror implementation and break on every refactor).
- In-memory databases (H2) standing in for PostgreSQL in repository tests.
Thread.sleepin tests; shared mutable state; dependence on time zones and the current date.- Many unique Spring contexts per suite;
@DirtiesContexteverywhere. - End-to-end tests for every edge case; no tests for error paths.
Glossary
- Test double: anything standing in for a real dependency in a test.
- Mutant: a deliberately altered program used to check that tests notice changes.
- Property: a statement that must hold for all valid inputs.
- Shrinking: reducing a failing random input to a minimal one.
- Test slice: a Spring test loading only one layer's beans.
- Flaky test: a test that passes and fails without code changes.