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
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?
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.
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.
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.
Every automated test, small or large, has the same four phases. The system under test (SUT) can be one class or a whole application.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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:
| Stub | Mock | Smart stub server | |
|---|---|---|---|
| Does | Returns canned replies | Returns replies and fails the test if the call never came | A programmable fake you configure over HTTP |
| Cares how often called? | No | Yes | Your choice |
| Best use | The default | Check a side effect, e.g. that Accounting was asked to authorize the card | Fake 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.
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.
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.
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.
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.
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 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.
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.
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.
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.
| Command | What it does |
|---|---|
npx jest or npm test | Run all tests once |
npx jest --watch | Live reload: rerun tests when code changes |
npx jest --init | Create the Jest config file |
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.
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.
Give each service its own automated path to production. Every push runs the tests, and deployment waits for a green result.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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
| Practice | Problem it solves | What it costs |
|---|---|---|
| Automated tests | Manual regression passes cannot keep up with independent releases | Test code to write and maintain |
| Test pyramid | A suite of slow, broad tests (snow cone) that is hard to debug | Narrow tests need code that can run in isolation |
| Test doubles (stubs, mocks) | Unit tests that are slow or fail because a dependency is down | Mocks make brittle tests; doubles can drift from the real thing |
| Solitary and sociable unit tests | Choosing how much to isolate each kind of class | Solitary tests bend when internals change |
| Dependency injection, design for testing | Code that hard-codes its dependencies cannot use doubles | Reshaping code, such as exporting a start function |
| Pipeline as a gate | Untested changes reach production when people skip tests | A gate is only useful if the suite is trusted |
| Quarantine flaky tests | Random failures teach people to ignore red builds | Time to find causes such as races and fixed waits |
| Run your own services, stub the rest | Running the whole system locally is slow and heavy | Stubs of other teams' APIs can go out of date |
Recap
- Independent releases need automated tests that run in seconds on every change; each test sets up, executes, verifies and tears down.
- Scope decides speed and confidence, so follow the pyramid: about ten times more tests with each step down, and avoid the slow, inverted snow cone.
- Test doubles keep unit tests fast and isolated: stubs return values, mocks also verify calls, and stubs should be the default.
- Test entities, value objects and sagas sociably, and domain services, controllers and message handlers solitarily, with dependency injection so the test can hand in doubles.
- Each service's pipeline runs the tests on every push and deploys only when they are green, so flaky tests must be quarantined and fixed before the team stops trusting the gate.
- Unit tests with stubs cannot tell whether two services still agree on their API; that needs the tests in the next chapter.
Quick check
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.
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.
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.
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.