All notes

Test Doubles Need Honest Proof Boundaries

Use fakes for decisions without pretending they reproduce transactions, networks or external systems.

English edition, edited for length. Read the complete Chinese original.

The simulation object placed the orders into an array, and the business test passed. However, after deploying the real database, errors occurred due to unique constraints, time zone conversions, and transaction rollbacks. The simulation object was not lying; it simply didn’t express these semantic aspects. The problem lies in the fact that the team expanded the scope of what the object was supposed to demonstrate.

The test double should be designed around the boundary, rather than being created solely to allow for the easy replacement of every dependency. To determine whether a test double is appropriate, you first need to answer the question: What does the test want to demonstrate? Is it a business decision, a call protocol, storage behavior, or a complete process?

Use surrogates to isolate instability, not facts.

The pricing rules require knowledge of the user’s tier. You can use fixed return values to test prices for different tiers. This type of testing primarily demonstrates pure business logic and does not require a real network. Clocks and random numbers are also suitable for explicit injection, allowing you to replay edge cases.

However, database transactions are different. In-memory arrays typically do not cause lock contention, unique conflicts, or commit failures, and therefore cannot be used to prove the correctness of concurrent inventory. If the test objective includes transactional semantics, a real database should be used, or at least, integration tests should be implemented to cover the key behaviors.

A third-party payment simulator can handle local error handling, but it cannot prove that your fields are currently accepted by the vendor. Controlled sandboxes or contract validation are required, along with clear documentation that they cannot fully replicate production risk controls and delays.

The stub provides pre-defined responses, the fake provides simplified but functional behavior, and the mock emphasizes the expected interactions. The spy records calls for later inspection. While the names are not absolute classification standards, they are helpful for discussing the scope of testing. A stub that returns a fixed order is suitable for verifying the display, a memory fake is suitable for simulating repeated business states, and a mock is suitable for verifying the parameters of calls to an unavailable supplier. Do not force all boundaries to use the same type of placeholder just for consistency.

Dummy systems are not inherently bad, and real systems are not inherently complete. Sandbox environments lack production-level security controls, and test databases are typically small. End-to-end environments may replace external services. By listing the real and replaced components at each level, you can identify which risks remain uncovered. Test reports should clearly state the database version and the vendor’s scenario, and should not be used as a guarantee of completeness.

Business logic should be as pure as possible, with dependencies concentrated in the adapter layer. This allows for rapid testing of most decisions and limited, real-world integration testing to verify transactions and protocols. Designing a single interface for adding functionality everywhere can also be overly complex. Abstraction should focus on expressing real replacement boundaries, rather than creating mock entry points for every private function. Testability comes from clearly defined responsibilities, not from the number of dependencies.

Excessive validation calls can freeze the implementation.

The test requires that the storage must be checked and updated once, and then refactored to perform atomic condition updates. This results in all tests failing. This assertion protects the steps, not necessarily the business outcome. Therefore, prioritize checking observable behavior unless the number of calls itself affects billing, rate limiting, or other non-repeatable side effects.

expect(result.status).toBe('reserved');
expect(await store.available('sku-1')).toBe(0);

If it’s necessary to prove that payment is only invoked once, clearly state this as a business constraint. However, be aware that a single invocation does not necessarily mean a single external execution: the results of the supplier after a timeout may be unknown, and the immediate success returned by the simulator can mask the most dangerous window.

Validating the call parameters is sometimes crucial, such as ensuring the correct currency and idempotent key are used. The focus should be on testing within the adapter layer, rather than having all higher-level tests rely on the internal object structure of a third-party SDK.

Even “Fake” Needs Contract Testing

While a shared interface for in-memory storage and real storage does not guarantee identical behavior, it is possible to establish a storage contract that governs how to handle identical scenarios across both implementations: how to handle duplicate identifiers, whether errors should occur when updating non-existent objects, and whether the list order should be stable.

An agreement doesn’t need to simulate all database behaviors. It should record the semantics that the business layer depends on. If the business layer relies on atomic operations, while the in-memory implementation only supports regular read/write operations, it’s not possible to declare them as interchangeable implementations. Modifying the interface to explicitly express atomic operations is more honest than secretly adding locks within the “fake” implementation.

Even a substitute database can accumulate complexity. A memory database with features like transactions, indexing, isolation levels, and retries typically indicates that the testing strategy is flawed. Maintaining a second storage engine is not the goal of the application team.

The storage interface requirements lack explicit updates and returns, while the in-memory implementation automatically creates records. This may protect against erroneous behavior during business testing. When running the same set of contract samples using both implementations, it’s possible to compare stable sorting, duplicate IDs, and state migration. However, the transactional and locking semantics cannot be fully covered by a shared contract, but the differences are at least explicitly marked, rather than continuing to claim complete interchangeability.

If “fake” begins to implement complex isolation and concurrency control, it should consider switching to a real database. The second set of databases are prone to inconsistencies even when they closely resemble real databases in dangerous scenarios. Testing speed can be improved by reusing controlled instances, parallel isolation, and reducing unnecessary initialization, without sacrificing real boundaries. Slow tests should first identify the bottleneck, then choose to replace it, rather than treating all integrations as unmaintainable.

Third-party adapters can perform regression analysis using recorded samples, but these samples may contain sensitive or personal data, which must be filtered before saving. Samples are reviewed upon protocol upgrades to ensure the vendor continues to accept requests. Controlled sandboxing verifies genuine interactions, while synthetic checks run within authorized and cost-effective parameters. Evidence layering prevents the need to repeatedly face the actual protocol after a single recording.

Incorrect paths require a time dimension

Instead of relying on direct exceptions, focus on covering the most basic failure scenarios. Real-world failures also include: the response being lost after the request is sent, partial results being returned, the operation completing but timing out, and repeated callbacks. When designing test doubles, it should be possible to express these different time points.

Don’t lump all exceptions under the Error('failed') category. Timeout errors, business rejections, authentication failures, and format incompatibilities require different handling. The overly broad error classification encourages a uniform retry logic, which can be problematic.

In concurrent testing, the “stand-in” (or mock) must also allow control over the execution order. Using explicit gates to pause a step and then restart the concurrent request is easier to reproduce than relying on random sleep. Sleep can only guess the timing, but cannot prove that a specific window has actually been opened.

To provide clear gating for dependencies:

  • Calling a request that has been issued but not responded to.
  • Submitting a business transaction but losing confirmation.
  • Disconnecting after partial output.

Testing: Waiting for the gate to open before issuing a second request can effectively create a competitive window. Fixed sleep on both fast and slow machines may not meet the prerequisites, and occasional failures cannot prove that the race condition is fixed. Observable phases and bounded waiting make it easier to pinpoint failures.

Using a simulated clock for timeout testing is suitable for verifying local timing logic. Real-world network cancellation still requires integration testing. Using a simulated clock does not guarantee that the actual fetch will release resources, and immediate rejection of mock responses does not prove that the upstream has stopped. Independently check error classification, retry budget, and final side effects. For operations that cannot be repeated, use a stable idempotent identity, and do not use mock call counts to verify the downstream state.

The following error types are preserved: business rejection, authentication failure, network uncertainty, and format changes. Consumers can safely fail when encountering unknown errors, without attempting to retry all exceptions uniformly. The test environment intentionally produces uncertain results, allowing for testing of state queries and manual recovery, rather than forcing each process to have only a success or failure outcome. A real system allows for interpretable unknown outcomes, which is safer than a false, deterministic failure.

Maintain a Small and Stable Real-World Environment

Real database testing does not necessarily require loading all production data. Each test should be based on the minimum business requirements, with isolated cleanup after each test to avoid shared states. To ensure that failures are explainable, it’s important to use a fixed database version, migration method, and necessary configurations.

When integration testing is slow, first check if each test case is repeatedly starting the infrastructure or performing a full migration, rather than immediately replacing everything with a simulation. You can reuse controlled instances according to test suites and isolate data using transactional or independent modes.

External sandbox testing should have a separate execution strategy to prevent failures caused by vendor issues from causing the entire local, purely logical testing to fail. However, the verification required before release should not be permanently skipped due to “instability.” Instead, the status should be clearly communicated to the deployment process.

The same database instance can be reused across packages, but data is isolated according to test transactions, schemas, or individual identifiers. Parallel use cases cannot share a fixed order ID and should not delete each other’s data; failures should not affect other users’ data. The migration version requires a fixed set of configurations, and testing should begin to confirm the actual environment without unexpected connections to production. Both real-world semantics and security isolation are required, and speed should not be prioritized over target validation.

The vendor sandbox requests have cost and rate limitations, and use a small number of key scenarios to avoid being blocked by network fluctuations during purely logical testing. Before release, the sandbox validation must report success, failure, or unavailability, and skipping a write should not be interpreted as a successful test. If the vendor experiences a failure, the decision to allow release will be based on policy, and the tool cannot automatically extend authorization. The scope of validation should be more reliable than simply showing a “green” status.

If a test fails, ensure that the necessary evidence is preserved: input version, stage, and associated identifiers, without saving all actual account details. Record HTTP samples, removing authentication headers and private fields, while maintaining the protocol structure of the synthetic values. After upgrading, re-validate the samples. New SDK error types may change, and if the old mock continues to throw generic errors, it will be impossible to detect and resolve regressions.

Regarding refactoring, business outcome testing should remain stable, while adapter layer interaction testing should only be adjusted when the protocol changes. If all tests fail after an atomic update, first determine whether they are overly locking implementation steps. Also, you should not ignore the actual side effects and parameters simply because you are “not testing the implementation.” Observable behaviors such as payments, messages, and fees should be tested. Test assertions should be chosen based on business outcomes.

Finally, maintain a comprehensive list of proof ranges, without complex charts: proof calculation at the rule layer, proof constraints and transactions at the storage layer, proof request-response at the protocol layer, and proof of task completion. If key boundaries are missed, supplement testing rather than simply increasing coverage. The success of a test double is to quickly identify issues, not to eliminate risks from the testing process.

The Trade-off Between Speed and Confidence

When choosing a substitute, it’s important to highlight the cost savings and the loss of verification. For example, unit tests for business rules don’t prove uniqueness constraints, real database tests don’t prove payment vendor compliance, and sandbox tests don’t prove production risk controls. The key invariant should have at least one appropriate real boundary, while other quick tests should cover a wide range of decisions. Coverage numbers alone cannot reveal these gaps; a thorough business risk review is required.

Both surrogate upgrade and interface upgrade should be maintained together. When a new atomic pre-reservation method is added, the surrogate must express the same return semantics, and the old, standard read/write interfaces should no longer be misused. Explicitly throwing an error for invalid behavior is more honest than simply returning a default success. A surrogate that always succeeds will make testing faster, but it may also mask underlying issues related to authorization and failure recovery. Testing tools also need to undergo code review and be provided with failure samples.

Clearly Defining Memory Replacement Responsibilities Based on Atomic Pre-Reserved Interfaces

The business logic relies on the reserve(sku, quantity) function returning success or failure, rather than first checking availability and then updating. The “fake” memory can express the return semantics and simple status. The real database adapter maintains atomicity through conditional updates. Both share a set of business contract tests, covering missing, duplicate, and quantity boundary scenarios. Lock waiting, unique constraints, and transaction rollback are also verified through the real storage test. The interface clearly defines the real operations, preventing the creation of dangerous read-write protocols in the fake environment.

If “fake” achieves complex MVCC, deadlock handling, and database error recovery, the maintenance costs are already approaching those of a second engine, and consistency is still not guaranteed. Reusing controlled database instances and reducing the need for full migrations and isolation testing data can improve performance. Identify the bottleneck in the test suite and avoid blaming the database itself for slow integration. A “fake” environment is suitable for isolating unstable and costly aspects, but it should not be used to isolate facts that are currently being verified.

Shared contracts also need to preserve the ability to differentiate. The implementation of sorting in memory may differ from the sorting rules in the database. It’s important to clearly define whether the business logic depends on these rules. The generator should create non-existent objects automatically, while the real repository rejects them. The same interface name should not be used to mask the differences. Invalid operations should clearly fail, making it more reliable than simply defaulting to success, ensuring that all business tests pass.

When a payment timeout occurs, three replacement time sequences are required.

The first scenario involves failure before acceptance, which may allow for a safe retry. The second scenario involves a successful operation but a lost response, requiring a query or idempotent operation with the supplier. The third scenario involves a clear business rejection, which should not be retried as a network error. A stub that immediately throws an Error only covers the most basic cases. A more robust solution would provide controlled gates and a synthetic execution counter, triggering the competition only after the exact stage has been reached, and not relying on fixed sleep guesses.

The payment check should only be called once. While it can sometimes mitigate billing-related side effects, a single HTTP call does not guarantee that the vendor will execute it only once, and recovery from unknown results still requires evidence of a valid protocol. The adapter layer should validate the currency, stable idempotency key, and payload, while the upper layer should verify the user’s results and recovery status. Each layer’s assertions should correspond to business consequences, and refactoring the SDK’s internal parameters should not cause all rule layers to fail simultaneously.

The vendor sandbox validation checks if the current request is accepted, but it may not implement production-level risk controls, real-time rate limiting, or delays. The sample recording protects parsing, but cannot permanently prove the vendor agreement. The sample removes authentication headers and private fields, using synthetic values to maintain the format. After upgrading the SDK, re-check error types and default retry values. The old mock continues to throw generic errors, making it impossible to detect these changes.

Verifying Fictitious Clocks and Real Resources Separately

A fast-forward clock is suitable for demonstrating timeouts, retries, and local state, but it does not simulate the network release that occurs after a real fetch is canceled. Unit tests verify the cancellation intent, and integration tests observe when upstream work stops. Promise.race only returns a timeout if the caller no longer waits; downstream processes may continue to consume resources. A placeholder should allow for expressing this difference, and not cause all aborts to immediately terminate the task.

Using only rules with injection timing and a random source allows for failures to be repeatable. The outer layer retains a small amount of real boundaries. Non-deterministic testing preserves evidence from the saved state and uses bounded waiting, without masking execution errors by extending timeouts. If the waiting condition is not met, the test reports a failure rather than indicating successful business operation. Whether the competition window is actually opened is part of the concurrent acceptance process.

Integrated Environment Isolation Should Not Impair True Semantics

Each test uses a unique identifier or pattern, and performs transaction cleanup as needed, preventing multiple tests from sharing a fixed order and deleting each other. The migration version has a fixed database configuration, and it is important to confirm that it is not used for production purposes before starting. The transaction rollback isolation cannot cover the submission of another independent connection, leading to the false assumption that all data has been cleared. In scenarios with multiple connections, it is necessary to clearly define the end and cleanup strategies.

Reusing instances reduces startup costs. Instead of completely redoing each use case, perform necessary migrations as part of a package. The degree of parallelism is limited by database capacity and testing responsibilities, and there is no unlimited creation of connections to shorten the overall duration. Representative data volumes also undergo performance testing, and the primary proof of minimal business integration is semantic. Small libraries quickly demonstrate that they do not support production throughput, and real-world technologies also have clear proof ranges.

External validation is not suitable for standalone reporting; the decision to block must be made based on policy. The term “skip” should not be used as “pass,” and it should not be used to permanently bypass the process due to temporary vendor outages. Pure logical testing still runs, and reliable layering prevents a remote state from making all local evidence inaccessible. The tool identifies gaps and does not arbitrarily expand the execution permissions for production operations.

Assertions and Assertions Interactions Must Have Justification

The number of times a query is executed before writing to storage is typically a matter of implementation details, and should be allowed to be changed to atomic updates. The number of times fees, payments, or irreversible notifications are sent is a business consequence, and must be protected. Do not remove important side-effect assertions using “only test behavior,” and do not use mocks to lock all private calls. Place query fields and authentication parameters in the adapter boundary validation, to reduce coupling with the vendor structure and achieve pure business results.

Intentionally modifying a unique constraint handler, losing a single confirmation, and triggering duplicate callbacks, revealing potential vulnerabilities. The test results list the coverage and gaps in the rules, storage, protocols, and key user tasks. While the overall coverage is high, there is no database contention test, and it does not prove the existence of inventory. A complete end-to-end test does not exhaust all monetary boundaries. The layers complement each other without exaggerating their individual capabilities.

Stand-ins also need to adhere to quality control measures

Fake, stub, and sample code are long-term maintenance assets, and should be reviewed together whenever new states or error categories are introduced. A successful default behavior can hide all permission and recovery issues, making it easier to identify and resolve problems. When validating against a real system, it’s important to maintain a clear understanding of the boundaries being tested and avoid creating false positives. Quick feedback is valuable, provided it doesn’t obscure important facts from the testing process.

The example contract also retains version and source information, and should be re-verified whenever the real adapter experiences semantic changes. The purpose is to enable new tests to pass by adding a special branch to “fake,” which will gradually transform it into a script that returns the expected answer based on the test name, losing its independent state model. The example should describe general, permissible behavior, rather than identifying and adapting to a specific test.

Commitment to Acceptance Review Testing

List the specific behaviors that are covered and uncovered by each test layer. Intentionally introduce unique conflicts, timeouts, and duplicate callbacks to verify that the corresponding layer can detect errors. If no layer covers a critical business invariant, it should be addressed rather than focusing solely on achieving a high overall coverage percentage.

Reliable testing isn’t about testing all dependencies, nor is it about connecting to all real systems every time. Instead, it ensures that the scope of each test is clear, and that at least one aspect of the real system is directly exposed to the test.

References