Chapter 14 of 27 · Part 7: Testing

Testing strategy and unit tests

FTGO's teams now change their services and frontends independently, many times a week, and nobody can check all of it by hand. This chapter shows how to decide which automated tests to write, how to isolate the code under test, and how to make tests guard every deployment.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 13 we split FTGO's user interface into micro frontends that each team deploys on its own, fed by BFFs and read models and kept fresh by events pushed to the browser. That left one problem open: with so many parts changing on their own schedules, how does anyone know it all still works?

This chapter

Which tests should FTGO write, how many of each, and how do they stop a broken change from reaching production? By the end you can balance a test pyramid, choose between stubs and mocks, unit test each kind of class in a service, and run the tests as a gate in each service's pipeline.

Manual testing cannot keep up

The monolith from chapter 1 had one release a month and a QA team that tested it by hand at the end. Microservices break that habit.

Problem

The Ordering team changes how Order Service calculates delivery fees and wants to ship the same afternoon. The QA team's manual regression pass takes two days and covers the whole app. Meanwhile the Kitchen, Delivery and Accounting teams also want to ship. Either every release waits in the QA queue, or teams skip testing and find bugs in production.

Solution · Automated tests

Write tests as code that runs in seconds, on every change, without a person. A developer edits Order Service, runs the tests with one keystroke, and sees the result before moving on.

The loop you want Edit code change Order svc Run tests one keystroke See result in a few seconds Repeat stay in flow Manual testing is slow and comes too late. Automated tests give this loop.

Every automated test, small or large, has the same four phases. The system under test (SUT) can be one class or a whole application.

Four phases of every test Setup build the fixture Execute call the SUT Verify assert outcome Teardown clean up SUT = System Under Test. It can be one class or the whole app.

Tests also exist for different reasons. The testing quadrants sort them by whether they face the business or the technology, and whether they check known behavior or explore for surprises. The checking half (Q1 and Q2) is what developers automate. Exploratory and usability testing stay manual. Load and robustness tests (Q4) come at the end of chapter 15, and security in chapter 16.

Marick quadrants Tests sorted by business or technology focus, and by checking or exploring. Q2 Business, verify functional and acceptance Q1 Technology, verify unit, component, integration Q3 Business, explore manual exploratory testing Q4 Technology, explore load, security, reliability
Cost

Tests are code: someone writes them, reviews them and keeps them working as the service changes. And "write tests" is not a plan. A team that tests every change through the browser ends up with a suite that takes hours.

How many of each test: scope and the pyramid

The question is not whether to automate, but which tests to automate, and how many of each.

Problem

After a bad release, the Ordering team writes 60 browser tests that click through the whole FTGO site, and only 20 unit tests. The suite now takes three hours. When a browser test fails, nobody knows whether Order Service, Kitchen Service, the gateway or the test environment caused it, so people rerun it and hope.

Split tests by scope: how much of the system is switched on while the test runs. FTGO uses four scopes. This chapter covers the bottom one; chapter 15 covers the rest.

Four kinds of tests, by scope Unit One class fastest Integration Adapter + infra DB, other service Component One service acceptance test End-to-end Whole app slowest

A unit test calls one function and starts no services, so thousands run in under a minute. A component test, also called a service test, starts one microservice and stubs what it calls. An end-to-end test drives everything, often through a browser. The word "integration test" means different things to different people, so say which scope you mean.

What each test scope covers Unit test Gateway, web UI: out Order: one function Accounting, DB: out Service (component) test Gateway, web UI: out Order: whole service Accounting: stubbed End-to-end test Gateway, web UI: in Order: in Accounting: in Example: the gateway and web UI call Order Service, which calls Accounting.

A wider scope gives more confidence that the parts work together, but the feedback is slower and a failure is harder to trace. A narrow test fails fast and points at the line, but proves little about the whole.

Trade-off of moving up or down the pyramid Wider scope (up) More confidence it all works Slower feedback Hard to find the cause Narrow scope (down) Fast feedback Failure points at the line Proves little about the whole When a big test fails, write a small one that would have caught it sooner.
Solution · Test pyramid

Write many fast, narrow tests at the bottom and few slow, broad tests at the top. A rule of thumb is about ten times more tests with every step down. When a broad test catches a bug, write a narrow test that would have caught it sooner.

The test pyramid End-to-end acceptance tests for the app Component acceptance tests for one service Integration service talks to its dependencies Unit business logic Top: slow, brittle, costly, so write few. Bottom: fast, reliable, cheap, so write many.

The opposite shape, with most tests at the top, is a test snow cone. It gives glacial builds, and a broken build stays broken for a long time because each fix takes hours to confirm.

Healthy pyramid versus test snow cone Healthy pyramid Snow cone (inverted) End-to-end End-to-end Service Service Unit Unit One system had 4,000 unit, 1,000 service and 60 end-to-end tests: too many slow ones. A snow cone gives glacial builds, so a broken build stays broken for a long time.
Cost

Narrow tests only work if the code under test can run on its own. But Order Service's classes call a database, Kafka and other services. A unit test that needs all of those running is not narrow and not fast.

Cut the dependencies: test doubles

To keep the bottom of the pyramid fast, the test must replace whatever is slow or not there.

Problem

A unit test for OrderController creates a real OrderService, which opens a MySQL connection and publishes to Kafka. The test takes seconds instead of milliseconds, and it fails whenever the shared test database is down, even though the controller code is fine.

Solution · Test doubles

Replace each dependency with a stand-in that the test controls. A stub returns canned values. A mock also checks that the SUT called it the right way.

Test doubles replace dependencies Stub Returns canned values to the SUT Lets the test run fast and alone Mock Also checks the SUT called it e.g. verify findById() was called Example: test OrderController with a Mockito double for OrderService.

Meszaros groups stubs, mocks, fakes, spies and dummies under one name, test doubles. The stub and the mock are the two you meet most often, plus a third kind used for whole services:

StubMockSmart stub server
DoesReturns canned repliesReturns replies and fails the test if the call never cameA programmable fake you configure over HTTP
Cares how often called?NoYesYour choice
Best useThe defaultCheck a side effect, e.g. that Accounting was asked to authorize the cardFake several downstream services at once in a component test (chapter 15)

Code can only use a double if the test can hand one in. Dependency injection means passing dependencies in, instead of hard-coding them inside the code.

Dependency injection makes mocking easy Hard-coded square(n) calls multiply() Test cannot swap multiply Injected square(n, multiply) Test passes in a fake Dependency injection: hand dependencies in, instead of hard-coding them.
Cost

Prefer stubs. Overusing mocks ties a test to how the code works rather than what it does, so every refactoring breaks tests. And a double is only as good as its author's idea of the real thing: if the real Accounting Service changes, the stub keeps returning the old answer.

What to unit test in a service

With doubles available, each kind of class in Order Service can get the style of unit test that fits it.

Problem

Order Service has entities, value objects, a saga, a domain service, a REST controller and an event consumer (from chapter 3 and chapter 9). Mocking everything around each class makes tests that break on every refactoring. Mocking nothing turns unit tests into slow integration tests.

Solution · Solitary and sociable unit tests

A solitary test isolates the class and replaces its collaborators with doubles. A sociable test uses the class with its real collaborators. Pick the style by the class's role.

Solitary versus sociable Solitary unit test Class under test only Dependencies are mocks Controllers, services, handlers Sociable unit test Class plus real collaborators Entities, value objects, sagas
Unit tests for each kind of class What to unit test Style and example Entities sociable · Order total Value objects simple · Money add/multiply Sagas sociable · CreateOrderSaga Domain services solitary · OrderService Controllers solitary · OrderController Message handlers solitary · OrderEventConsumer

Entities and value objects are plain code with no infrastructure, so test them sociably: create an Order, add line items and check the total; add and multiply Money values. A saga is tested sociably too, with a test DSL that fakes the database and the broker. The test starts the saga, plays the replies from other services, and checks which commands it sends. Test the happy path and every rollback path.

Unit testing a saga Test CreateOrderSaga Consumer svc Kitchen svc start saga ValidateOrder cmd fake success reply CreateTicket cmd assert the commands sent Test the happy path and every rollback path. The test DSL fakes the database and broker.

Domain services, controllers and message handlers mostly coordinate other objects, so test them solitarily. For OrderService.createOrder(), stub the repository, call the method, and verify that it saved the order, published the event and created the saga. For OrderController, use a Mockito double for OrderService and check the HTTP response.

Solitary test of a domain service Test OrderService Mocks stub repository createOrder() save order publish event create saga verify the calls
Cost

Solitary tests verify calls, so they still bend when the code inside changes. Some code is also hard to reach: a service whose start-up code connects to its database and starts listening the moment the file loads gives the test no place to slip in a double.

A unit test in practice with Jest

The same ideas apply in any language. Here is a short side example from FlixTube, the Node.js video app you build in chapter 26, tested with Jest.

Problem

FlixTube's metadata microservice starts an Express server and connects to MongoDB as soon as index.js loads. A test cannot run it without a real server and database, and cannot swap the libraries for fakes.

Solution · Mock the libraries, design for testing

Export a startMicroservice function and only run it automatically when the file is the entry point. The test then mocks Express and the MongoDB library, calls the function, and checks what the code did with the fakes.

Unit test of the metadata microservice Jest runs index.test.js Test mocks Express, DB Service code startMicroservice Fake libraries no server, no DB Nothing real starts, so hundreds of such tests stay fast.

The test file sits beside the code as index.test.js. A describe block names the suite, each test runs the code, and expect checks the result. One useful test checks that the service starts and that its /videos route reads from the database. Mocking also removes slow work such as database queries, network calls and file access, so hundreds of these tests stay fast.

CommandWhat it does
npx jest or npm testRun all tests once
npx jest --watchLive reload: rerun tests when code changes
npx jest --initCreate the Jest config file
Design for testing: reshaping code so tests can call it is normal. It is how test-driven development nudges design.
Cost

The suite is fast and runs on a keystroke, but only when someone presses the key. Under deadline pressure, people do not.

Make tests a gate: one pipeline per service

Tests only pay off when they run on their own.

Problem

On a Friday afternoon a developer deploys a quick Order Service fix without running the tests. One unit test would have caught the bug in a second. Instead, orders with a promo code fail all evening.

Solution · Deployment pipeline as a gate

Give each service its own automated path to production. Every push runs the tests, and deployment waits for a green result.

Automated tests gate deployment Push code and tests CI runs tests npm test Gate pass or fail Deploy only when green Docker and Docker Compose keep the test environment close to production.

A pipeline orders the tests by the pyramid. Fast checks come first and stop a bad change within minutes; slower stages that run closer to production come later. Chapter 21 builds such pipelines in detail.

A deployment pipeline per service Commit stage compile, unit, lint Integration adapters, contracts Component service in isolation Deploy to production Early stages are fast feedback. Later stages are slower and closer to production.

Aim for hundreds or thousands of fast unit tests, fewer integration tests and very few end-to-end tests: developers skip slow tests. The line between test types is blurry, since all tests sit on a spectrum of scope. Docker and Docker Compose keep the test environment close to production.

Test independently: if teams deploy independently, they should test independently, ideally in their own environment. Research summarized in a delivery study found that high performers do most testing on demand, without a shared integrated test environment.
Cost

A gate is only useful if people trust it. With more moving parts, more tests fail for reasons that have nothing to do with the change, and a gate that cries wolf gets ignored.

Keep the suite trusted: flaky tests and fast loops

More services mean more ways for a test to fail by accident: a service is down, the network glitches, two threads race, or a time-out hits.

Problem

One Kitchen Service test fails about one run in ten because it waits a fixed 2 seconds for an event. The team learns to press "rerun". A month later a real bug makes the same test fail, and someone presses "rerun" until it passes.

A test that sometimes fails and is simply re-run is flaky. Teams drift into normalization of deviance: they get used to a suite that "always fails like that", and real breakages hide in the noise.

Solution · Quarantine and fix flaky tests

Treat a flaky test as a bug. Take it out of the gate at once, find the cause, and fix it or replace it with a smaller, deterministic test. Sometimes the best fix is to change the software so it is easier to test.

Handling a flaky test Fails at random people rerun it Quarantine out of the suite Find the cause threads, network Fix or replace smaller test Track flaky tests down, and remove them from the suite if you cannot fix them now.

The same thinking applies to a developer's own machine. As the number of services grows, running all of FTGO on one laptop hurts. Moving development to the cloud lengthens the edit-and-test loop instead. Run only the services your team owns, and stub the rest.

Where developers run services Run for real Services your team owns Stub Other teams' services Avoid Whole system locally Cloud dev: slow loop Fast local feedback beats running everything. Stubs fill the gaps.
Cost

Fast local loops and stable suites rely on stubs of other teams' services. A stub is a guess about another team's API, and nothing yet checks that the guess is still right.

What unit tests cannot see

The pyramid so far tests each service alone. FTGO's services work only together.

Problem

The Ordering team renames a field in the order response. Every Order Service unit test passes. The API gateway's tests also pass, because they use a stub of Order Service that still returns the old field. Both pipelines go green, both deploy, and the order page breaks in production.

Every pair of FTGO services that talks has an implicit contract, in one of three interaction styles from chapter 4 and chapter 5:

Interactions that need testing REST Client → service API gateway → Order Pub/sub Subscriber ← publisher Order History ← Order Async req/reply Requestor → replier Order → Kitchen Every pair of services has a contract. Testing both together is an end-to-end test, which you want to avoid.

Testing both sides of each pair together would mean an end-to-end test, the slow, brittle top of the pyramid. The next chapter shows tests that check these seams, the adapters and whole services without paying that price.

Cost

A well-shaped pyramid of unit tests with doubles is fast and trusted, but it proves each service is right only against its own assumptions about the others.

Practices in this chapter

PracticeProblem it solvesWhat it costs
Automated testsManual regression passes cannot keep up with independent releasesTest code to write and maintain
Test pyramidA suite of slow, broad tests (snow cone) that is hard to debugNarrow tests need code that can run in isolation
Test doubles (stubs, mocks)Unit tests that are slow or fail because a dependency is downMocks make brittle tests; doubles can drift from the real thing
Solitary and sociable unit testsChoosing how much to isolate each kind of classSolitary tests bend when internals change
Dependency injection, design for testingCode that hard-codes its dependencies cannot use doublesReshaping code, such as exporting a start function
Pipeline as a gateUntested changes reach production when people skip testsA gate is only useful if the suite is trusted
Quarantine flaky testsRandom failures teach people to ignore red buildsTime to find causes such as races and fixed waits
Run your own services, stub the restRunning the whole system locally is slow and heavyStubs of other teams' APIs can go out of date

Recap

Quick check

You replace OrderService with a double and check that OrderController called findById() once. Stub or mock?
Show answer

A mock, because the test verifies the call. A double that only returned a value would be a stub. This is a solitary unit test.

FTGO's Kitchen team has 20 unit tests and 60 browser tests, and the suite takes three hours. Failures are often rerun until they pass. What is wrong, and what should they do first?
Show answer

The suite is a test snow cone (an inverted pyramid), and its flakiness has taught the team to ignore failures. Quarantine the flaky tests, replace slow broad tests with smaller unit and component tests that catch the same bugs, delete duplicated coverage, and make the suite fast enough to gate every push.

Order Service and the API gateway both have full unit test coverage and green pipelines, yet the order page breaks after a release. How is that possible?
Show answer

The gateway's tests use a stub of Order Service, and the stub still returns the old response. Each side is tested only against its own assumptions about the other. Checking that the two still agree needs a contract test, covered in chapter 15.

Still open

Unit tests prove each piece of a service right in isolation. They cannot tell us whether the service works with its real database and broker, or whether FTGO's services still agree with each other.

Next: 15 Integration, contract and end-to-end tests →