Automated Tests
All four categories may depend on the frameworks and libraries. Those arrows are left out to keep the number of arrows manageable.
The Core and the humble objects are shaped the way they are so that the majority of your tests can run entirely in memory. Unit tests can be used to verify the Core's behavior, even in edge cases, while Integration and End-to-End tests can verify that all parts work together on the happy path as expected.
The history of testing is long, so let us look back on how it evolved in the era of Agile Software Development.
A little history on testing
Test Pyramid and Test Diamond
Automated testing became mainstream around 2000 with Extreme Programming and the xUnit family of frameworks. A few years later the discussion turned to which kinds of tests exist and the associated costs, and around 2004 the test pyramid appeared - coined by Mike Cohn, popularized by Martin Fowler, and refined by Lisa Crispin and Jason Huggins. It originally described three layers:
- Unit tests - easy to write and maintain, fast to execute, aimed at small parts of the system.
- Service tests - a call into a high-level API, typically involving third-party systems such as databases, web services, or message brokers.
- UI tests - the whole system end to end, historically through recorded scripts driving the user interface.
The argument was already clear back then: service and UI tests are more expensive to build and maintain because third-party systems are involved, and they are slower to run. Recorded UI tests are also brittle - a layout change breaks them. Hence the shape: many unit tests, fewer service tests, fewest UI tests.
In the 2010s, Docker arrived, and with it David Heinemeier Hansson's 2014 article TDD is dead. Long live testing. A movement formed around the Test Diamond: write mostly integration tests, spin the third-party systems up in containers inside the test run, and test components in interaction rather than in isolation.
This also led to a redefinition of the layers: we now typically speak of Unit Tests, Integration Tests, and End-to-End Tests. David Heinemeier Hansson's main critique of the Test Pyramid was the enormous amount of Test Doubles that a unit-test-heavy suite requires ("writing mocks that return mocks"), and the resulting design damage on the production code, as can be seen in this discussion between him, Martin Fowler, and Kent Beck.
What exactly is a "Unit"?
This critique might stem from a misunderstanding of what "Unit" actually means. Martin Fowler's bliki entry settles on three points: unit tests are low-level and focus on a small part of the system, they are written by the programmers themselves with a unit testing framework, and they are expected to be significantly faster than other kinds of tests.
Beyond that, two approaches to writing Unit Tests matter: Solitary vs. Sociable. A Solitary test replaces every collaborator of the system under test with a test double. A Sociable test allows other units to participate. There are also associated names: Mockist vs. Classic Style. Mockist style prefers solitary tests and mocks everything. Classic style prefers sociable tests and uses doubles only where it must.
It is imperative to understand that representatives of the Agile Movement like Martin Fowler and Kent Beck write Sociable Tests. David Heinemeier Hansson uses Mockist style with Solitary Tests, resulting in the huge amount of test doubles.
CHACK's definition of Automated Test Categories
CHACK recognizes that the definition of Unit Tests is vague, thus it redefines the three layers of Automated Tests in an unambiguous way:
- Unit Tests run entirely in memory. They mainly exercise types in the Core and are written preferably as Sociable Tests. They target higher-level APIs first with referenced lower-level Core components being part of the same test, reducing the need for Test Doubles. Where the system under test would perform an I/O call, the Humble Object is replaced by a test double. These tests cover both the happy path as well as error and edge cases. There is one deliberate exception: the local file system does not disqualify a Unit Test. It is available in every context - development machine, CI/CD pipeline, container - and it is fast and stable. Humble Objects that only access the local file system may therefore take part in a Unit Test as collaborators, but never as the system under test.
- Integration Tests exercise a whole feature through its entry point, with the application assembled by the real Composition Root, and perform at least one real I/O call to one third-party system in another process: a database server, a web service, a message broker, SAP - you name it. An integration test may still use test doubles for certain abstractions, as long as one genuine I/O call happens. These tests focus on happy paths because failures and edge cases are typically hard to replicate in real-systems running in a Docker container or in staging environments.
- End-to-end tests allow no test doubles at all. Every I/O call goes to a real instance of the real system, in a configuration as close to production as you can make it. They are the most expensive tests to build and run, and like integration tests they mainly cover the happy path.
Every test belongs to exactly one of these categories. Here they are side by side:
| Category | System under test | I/O | Test Doubles |
|---|---|---|---|
| Unit | Core types, preferably the feature's endpoint | None, except the local file system | Replace Humble Objects, except those that only access the local file system |
| Integration | A whole feature through the real Composition Root | At least one real third-party system | Allowed for other third-party systems |
| End-to-End | The whole system, running as it does in production | All real | Not allowed |
This approach is taken for two reasons:
Performance Costs of Integration Tests
The first reason is cost. You can run many thousands of Unit Tests in a few seconds, or 2 to 3 Integration Tests. I/O calls are not a little slower than in-memory operations, they are one million to one billion times slower.
Logarithmic scale: each grid step is 10× longer. The baseline is 0.001 ns.
- In-memory operation: Static method0.0082 nanoseconds
- In-memory operation: Instance method0.0855 nanoseconds
- In-memory operation: Call via interface0.4322 nanoseconds
- In-memory operation: Call via overridden method0.3243 nanoseconds
- In-memory operation: Call via delegate0.6514 nanoseconds
- In-memory operation: New struct0.0052 nanoseconds
- In-memory operation: New class2.9059 nanoseconds
- In-memory operation: Throw and catch exception3,540 nanoseconds
- In-memory operation: Lock4.5182 nanoseconds
- In-memory operation: Thread pool1,307.2671 nanoseconds
- In-memory operation: New thread85,300.6974 nanoseconds
- In-memory operation: List: 100 strings Contains265.122 nanoseconds
- In-memory operation: List: 1,000 strings Contains2,712.136 nanoseconds
- In-memory operation: Dictionary: 100 strings ContainsKey8.809 nanoseconds
- In-memory operation: Dictionary: 1,000 strings ContainsKey8.377 nanoseconds
- Database read: Load document from RavenDB (same computer)194,500 nanoseconds
- Database read: Load entity from MS SQL (same computer)245,100 nanoseconds
- Database read: Load entity from Oracle (VPN)20,300,000 nanoseconds
The horizontal axis is logarithmic by default: every grid step is a factor of ten. Switch to linear scaling to see how the slowest operation dominates. You shouldn't focus on the absolute values of this setup, but rather on the differences between these values. They determine how long you sit waiting before you know whether your change works.
Writing Tests for Errors and Edge Cases
The second reason is coverage of the unhappy paths. Integration tests are excellent at the happy path and at proving that the pieces fit together, even across process boundaries. They are bad at edge and error cases: reproducing a deadlock, a timeout, a truncated response, a unique-constraint violation, or a broker that rejects a message on demand is hard to do reliably and often ends in a flaky test. With a test double, injecting that exact failure and asserting how the Core reacts is straightforward.
What tests may depend on
The diagram at the top of this page splits the Automated Tests box into its parts, because the three kinds of tests do not point at the same things.
The system under test of a unit test is always in the Core. Never a humble object, never a component of the Composition Root. Humble objects are replaced by test doubles that implement the same I/O abstraction; that is the entire reason those abstractions exist. Reusing a piece of the Composition Root inside a unit test is fine - for example, building a DI container in the setup phase to assemble the object graph - but the Composition Root is the fixture, not the system under test. Starting a host is a different matter, as you'll see in the next section.
Test doubles implement the I/O abstractions. Because of them, the system under test can stay in-memory during a test run, and it is why the diagram draws the test doubles pointing at the I/O abstractions rather than at the humble objects. A test double is a second implementation of the same abstraction, written for the test.
Integration and end-to-end tests may touch everything. Their point is realism: they use the real humble objects and the real Composition Root, so that the fixture resembles what runs in production. They also reach the third-party systems directly - starting a container, seeding a database, publishing a message. Depending on your test setup, they run inside the test runner process (e.g., via Testcontainers) or outside of it (e.g., via Docker Compose). Integration tests may add test doubles where they need to; end-to-end tests may not.
Humble Objects are never the system under test, in any category. Integration and end-to-end tests aim at a feature or at the whole system. The Humble Objects take part and are verified along the way, as part of that feature. The same holds for the Composition Root: it helps set up the test, but it is never what the test aims at.
Sociable Tests: Aim your tests at the most abstract API of a slice
Imagine you implement a feature - an HTTP endpoint, or a subscriber that handles a message from a broker. Typically there will be an entry point and one or more services below it holding the actual logic, plus the I/O abstraction for the database.
The tempting approach is one test class per type: test the endpoint with a mocked service, test the service with a mocked repository, test the validator on its own. You end up maintaining a web of test doubles that mirrors your class structure, and every refactoring below the surface breaks tests, even when behaviour did not change. A typical scenario for solitary tests.
CHACK does the opposite. Write the test against the most abstract API of the slice - the endpoint - and let the real service, the real validator, and the real mapper participate. Only the humble object is doubled. The benefits are immediate:
- Few test doubles.
- You are free to refactor everything below the endpoint - split a service, merge two types, rename a method - without breaking a single test, as long as the observable behaviour is unchanged.
- The test reads like a description of what the feature does, because it enters through the same door the outside world uses.
Call the endpoint directly. A Unit Test calls the endpoint method itself, just like the framework would after it has received and deserialized a request. It doesn't start a host - no web server, no in-memory test server, no application host of any kind. A host brings routing, serialization, middleware, and the rest of the framework pipeline with it, and making sure that all of this works together is exactly what Integration and End-to-End Tests are for. Your Unit Tests stay fast and focused on the decisions your code makes.
Test doubles at the level of the slice's high-level API therefore stay coarse-grained on purpose.
Close coverage gaps with Solitary Tests. Some code is hard or impossible to reach from the endpoint. Guard clauses are the typical example: when the callers of a lower-level type make sure that they never pass invalid arguments, the guard clauses of that type are never hit by a Sociable Test. A Solitary Test calls the method directly and checks that the guard clause is in place. Intricate calculations with many edge cases are another good candidate, because testing each case through the endpoint would bury the interesting part under setup.
Overall, strive to keep the number of test doubles low.
Keeping the test suite fast and reliable
A test suite only helps you when you can trust it and don't mind running it. A few habits make a big difference here.
Start third-party systems inside the test run. Tools like Testcontainers for Integration Tests and Docker Compose for End-to-End Tests make your suite self-contained and reproducible: everything it needs comes up when the tests start. Running against a shared, always-available test environment also works, but be aware of the trade-off: if that environment is only reset periodically, data-manipulating tests will eventually collide with their own leftovers and the chance to encounter flaky tests rises.
Start each system once per test run. Starting a database or a message broker takes seconds. When every test or every test class starts its own, those seconds add up quickly, and the test run gets longer with every class you add. Start each third-party system once, before the first test needs it, and let all tests run against it.
Give each test its own data. Tests that share a system shouldn't get in each other's way. Each test works with data of its own - unique IDs, its own database or schema, its own queue - so that it doesn't matter which other tests run before it or at the same time.
Keep tests independent. Each Unit Test can run on its own, in any order, and fails for exactly one reason. The same is true for Integration and End-to-End Tests, with one exception: a scenario that proceeds step by step, where the outcome of one test is the setup for the next - say, registering a customer, then placing an order, then cancelling it. That's fine, as long as the execution order is made explicit, so that nobody has to guess it, and neither does the test runner.
Don't repeat what other tests already cover. Within the same context - usually the same test class - each Integration or End-to-End Test adds something new. When two of them run through the same steps, the second one makes the suite slower without telling you more. Unit Tests are cheap enough to cover every edge case; Integration Tests are not, and they don't need to be, because the Unit Tests already do.
Test Doubles
When we talk about test doubles, it helps to share a vocabulary. CHACK uses the one from Gerard Meszaros' xUnit Test Patterns. The kind of a test double is not determined by how it is implemented, but by how the test uses it:
- as a control point for the indirect inputs of the system under test - the values it receives from its dependencies,
- as an observation point for its indirect outputs - the calls it makes to its dependencies,
- or as neither.
This gives the following kinds:
- A Dummy is passed to satisfy a parameter, but the system under test never uses it.
- A Stub is a control point. It provides predefined answers, or throws predefined exceptions, in response to the calls made by the system under test.
- A Spy is an observation point. It records the calls made by the system under test so that the test can verify them afterwards. It may also return predefined answers.
- A Mock is an observation point, too, but it is configured with expectations before the exercise phase and verifies by itself that the system under test called it as expected. It may also return predefined answers.
- A Fake is neither a control point nor an observation point. It is a working, lightweight implementation of a dependency that behaves self-consistently: data passed in by earlier calls is returned by later calls. A dictionary-based implementation of a Session abstraction, an in-memory database, or a fake web service are typical examples. Unlike Stubs and Mocks, its answers are neither hard-coded nor configured per test - although a test may seed its state.
- A Null Object is a special Fake for operations whose only effect is a side effect: it is called by the system under test, does nothing, and returns nothing.
Naming a test double after the kind it actually is helps the next reader understand the test. A Test Double called FakeOrderSession that returns hard-coded answers is really a Stub, and one that records calls is a Spy - with the right name, you know at a glance whether the test controls inputs or observes outputs. A Null Object may be called Null… instead of Fake….
Testing in .NET shows Unit Tests, Test Doubles, and Integration Tests with xUnit, ASP.NET Core, and Testcontainers.