Integration tests
Tests that check components working together, including real databases or services.
Integration tests catch problems that unit tests miss, at the boundaries between parts. They are slower but often give more confidence per test. Many teams find them the best value for typical product code.
Why it matters for a product engineer
Integration tests check that parts work together: the code with the database, the API with its handler, the app with a partner’s service. Many bugs live at these boundaries, where unit tests cannot see them. Integration tests are slower than unit tests, but they often give more confidence per test. Kent C. Dodds sums it up: “Write tests. Not too many. Mostly integration.”
How to do it
- Test a feature through its real entry point, such as an HTTP route or a command, with a real database.
- Replace only what you do not control, such as third-party APIs, and keep the rest real.
- Record real responses from external services once, and replay them in tests.
- Give each test its own data, so tests can run in any order and in parallel.
- Assert on what a user or caller would see: the response, the saved record, the email sent.
- Keep the slowest tests out of the main loop if they block people, but keep them in CI.
Common mistakes
- Mocking so much that the test only checks the mocks.
- Tests that call a live third-party API, and fail when it is slow.
- Shared test data, so one test breaks another.
- Only unit tests, and every bug found at the boundaries in production.
Example
Segment sends events to over 140 destinations, each a partner API. Its tests used to call those APIs over the internet. These calls were the main cause of failing tests, some destinations took up to five minutes, and the whole suite up to an hour. The team built Traffic Recorder: the first run records each request and response to a file in the repository, and later runs replay the file.
How Segment's Traffic Recorder runs a test
After the change, the tests for all 140+ destinations ran in milliseconds, and expired credentials or a slow partner no longer failed them.
ReportedTwilio Segment, 'Goodbye microservices'
Sources: The testing trophy and testing classifications (Kent C. Dodds) ↗ · The practical test pyramid (Ham Vocke) ↗ · Goodbye microservices (Alexandra Noonan, Twilio Segment) ↗
Resources
2- articleStart here
The testing trophy and testing classifications ↗
Kent C. Dodds · 8 minAn argument for leaning on integration tests in product code, where they give the most confidence per test.
- articleGo deeper
The practical test pyramid ↗
Ham Vocke (martinfowler.com) · 2018 · 55 minA thorough, code-heavy guide to unit, integration and end-to-end tests and how many of each to write.
Tools
2- ToolOpen source
- ToolOpen source