Unit, integration, E2E, mocks, TDD and test design
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeThe test pyramid is a strategy that suggests having many unit tests, fewer integration tests, and even fewer end-to-end tests. It's important because it helps maintain fast, reliable, and maintainable test suites by balancing coverage and cost.
I use the Arrange-Act-Assert pattern: first, I set up any necessary data or mocks, then I execute the function under test, and finally I assert that the result matches the expected outcome.
Unit tests should be isolated so they don't depend on external systems or shared state. This ensures they run quickly and consistently, making it easier to pinpoint failures.
A mock is an object that simulates the behavior of real dependencies and allows you to verify interactions. I use mocks when I need to check if a function calls another service or method as expected.
A stub provides predefined responses to method calls, while a fake is a simplified implementation that mimics the real dependency. Fakes are useful for testing logic with lightweight substitutes, whereas stubs are mainly for controlling outputs.
I use Testcontainers to spin up real database containers during integration tests. This lets me test against actual database behavior without affecting production or development environments, and ensures clean setup and teardown.
Flakiness often comes from timing issues, network instability, or reliance on external systems. I address it by controlling test data, minimizing dependencies, and using retries only when necessary to avoid masking real issues.
TDD involves writing a failing test first, then implementing code to pass the test, and finally refactoring the code and tests for clarity and maintainability. This cycle helps ensure code is well-tested from the start.
Code coverage shows how much of your code is executed by tests. It's useful for spotting untested areas, but high coverage doesn't guarantee correctness or meaningful assertions.
Contract testing verifies that services adhere to agreed interfaces, catching mismatches before deployment. This prevents integration bugs and ensures smooth communication between microservices.
I start by writing characterization tests to capture the current behavior of legacy code. This lets me refactor or add new tests without risking breaking existing functionality.
I use mocks when I need to simulate behavior and verify interactions, and spies when I want to record how functions are called without changing their behavior. The choice depends on whether I need to control outputs or just observe calls.