All notes

Contract Tests Should Protect Real Consumer Dependencies

Verify the interface a consumer uses without freezing every incidental provider detail.

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

The order interface changed total from a number to a string, and all backend unit tests passed. However, the frontend concatenated the amount incorrectly, resulting in an erroneous result. The provider demonstrated their new implementation, but failed to prove that consumers relying on the old behavior would still function correctly. This is a boundary issue that contract testing is well-suited to address.

A contract isn’t about rigidly defining every return field, but rather about expressing the actual request-response rules that the consumer relies on. It should be strict enough to detect harmful changes, but also restrained enough to prevent normal evolution from being blocked by the addition of irrelevant fields.

Creating the Smallest Possible Example from Real Dependencies

Assume that the billing page only requires the order identifier, the minimum currency unit amount, and the currency. The tests should demonstrate that these fields exist, have the correct data types, and that empty orders and authorization issues can be handled. Do not include irrelevant information such as creation time and internal audit fields.

{
  "id": "order-42",
  "amountMinor": 1250,
  "currency": "CNY"
}

The meaning of the amount field also needs to be clarified: whether negative numbers are allowed, how refunds are expressed, and which currency set the field belongs to. Simply validating that the JSON field is a number cannot prevent the provider from converting “yuan” to other currencies without changing the field name. Changes in meaning often require documentation, versioning, and migration, which cannot be solved solely by a matcher.

Consumer testing should actually invoke your own parsing or adaptation code, rather than manually asserting a single, isolated example. Otherwise, even if the frontend reads an incorrect field, the contract file may still appear to be correct.

The order identifier can match a valid format, the amount can be restricted to a limited integer range, and the currency can be validated based on the consumer’s actual supported range. If all fields are fixed to example values, providing a valid test order will also fail. If only the existence of the object is checked, destructive type changes will still pass. Each matcher corresponds to a reason for dependency, avoiding the need to change all values to arbitrary strings in order to reduce failures.

The array contract also needs to express the concept of an empty set, order, and element structure. Consumers rely on reverse chronological order, but the contract only checks a single record, making it impossible to detect sorting violations. It is possible to retain a small number of meaningful state and result relationships without recording every single data item. Paging cursors and fields like “hasMore” should also be used according to the consumer’s workflow. Isolated snapshot responses cannot prove that the pagination conditions are consistent.

The enumeration extension requires discussion of consumer strategies. The backend can add states, while the frontend should either display “invalid” or guarantee a limited enumeration. Both options affect compatibility. Once the contract exposes the actual dependencies, the team can adjust any overly strict requirements, preventing the client from making incorrect assumptions about all known states. Testing should be a collaborative agreement, not a tool for one team to restrict another.

Provider Status Enables Case Replay

The provider needs to be able to verify business states that can be repeatedly set, such as the existence of a paid order or a user having no access permissions. The state preparation should be decoupled from the production implementation, but it must generate real business-allowed data.

Do not rely on a specific order that happens to exist in the shared test environment during validation. If the test fails due to cleanup tasks, it will become a random alert. Also, do not create sample data by directly inserting data that violates business constraints, as this could cause the validation to incorrectly identify a production path that will never occur.

The state preparation phase is solely responsible for establishing the preconditions; it should not secretly modify the implementation of the response to adapt to the contract. The boundaries between the testing tools and the application must be clear to avoid false success, such as “only returning the correct structure in test mode.”

The test entry should use the same serialization and error handling as the production environment. State preparation only controls the data preconditions. If the mock handler returns a contract sample, the tool can only verify that the sample matches itself. Whether to include a real database depends on the verification goals, but the provider’s implementation cannot be replaced. There is also testing for the correctness of database transactions, which focuses on the consumption of requests to responses.

The authentication and authorization status must also be replayable. Use a test identity to establish legitimate permissions, and verify that error states conform to the expected structure for the consumer code. It is not sufficient to only verify the successful structure after disabling all authorizations in test mode. The allowed list of sensitive data is also crucial; contracts should not require the return of private fields that are not needed on the front end. New fields are often compatible, but may introduce privacy issues. Compatibility is not a substitute for a thorough security review.

The tool version, contract version, and provider-specific identifier are all saved together, and the verification records correspond to specific code. Shared environment data drift can lead to unstable results. Maintaining a minimal, controlled state and independent resources can reduce volatility. Do not circumvent release restrictions for an extended period solely due to testing instability. Instead, first investigate whether the state, dependencies, and testing scope are correct.

Each file (contract or pattern) should have its own security layer.

OpenAPI or JSON Schema description providers offer a common interface that consumers rely on. The consumer contract description specifies the exact interactions that a consumer actually depends on. The former is suitable for generating documentation and structural validation, while the latter is suitable for discovering dependency conflicts when services are independently published.

Neither can fully demonstrate the complete business process. Whether users receive the correct items after submitting an order still requires appropriate end-to-end testing or business integration testing. Contract testing should not be solely responsible for database transactions, queue delivery, or cross-system reconciliation.

The testing strategy can be divided based on failure points:

  • Unit tests answer how the local code handles data.
  • Contract tests answer whether the interactions between the two parties are compatible.
  • End-to-end tests answer whether the key business paths are completed.

The number of tests at each level should be adjusted based on risk, and does not necessarily follow a fixed pyramid ratio.

Entering the Verification Process in the Order of Publication

Consumers are preparing to use a new field, but the provider hasn’t yet launched it. Therefore, consumers should not be released solely based on successful validation in the current development branch. It is necessary to clearly identify which versions of the provider have been validated for this contract in the target environment.

The consumer declaration can be used as a basis for changes, but it needs to be clearly defined in terms of its scope of use. For example, a specific field should only be read in the refund exception branch; normal successful examples should not reveal dependencies. The contract samples should cover these branches. The provider can check the contract shape, but the consumer still needs to verify its own business mapping to avoid both parties only proving the same successful screenshot.

Save contract versions and verification results to allow the access control system to answer the question, “Can these two versions run together?” If the access control system is frequently bypassed manually, investigate whether the contract is too lenient, the environment is unstable, or the team’s release agreement is not being properly enforced.

When a provider removes a field, it needs to know which consumer versions are still deployed, rather than just looking at the latest branch. Offline users on mobile devices and external API clients may exist for a long time, and compatibility windows or version interfaces cannot be automatically shortened by a central contract library. To determine whether a combination is allowed, it is necessary to register active versions and verify their relationship. If the consumer scope is unknown, a clear policy is required, and it should not be claimed that the tool covers all customers.

When a consumer introduces new fields, the process involves: first, deploying a compatible provider; second, verifying the target environment version; and finally, deploying the consumer. The provider then removes the old fields, and this requires the old consumer to be decommissioned. This sequence is similar to the “expand-contract” pattern in databases, but the migration itself is not performed. Contract validation provides evidence of compatibility, and the deployment system is responsible for ensuring the correct order and rollback capabilities.

Reasons, risks, and durations for preserving manual exceptions. Frequent exceptions may indicate that the contract is locking unrelated fields, or that the team is unwilling to address genuine incompatibilities. In either case, different solutions are needed. Access control systems should not only have red lights; errors should be clearly identified, specifying the exact interaction and matching failure. This will help both sides decide whether to adjust the implementation or modify the contract appropriately.

Learning from Failures is More Valuable Than Following a “Happy Path”

Empty fields, adding new values to an enumeration, pagination with no results, and business rejections are often more likely to negatively impact consumers than normal orders. The display of unknown enumeration values should be designed by the consumer, rather than requiring the provider to never be able to add new states.

Date strings should also clearly specify the time zone and parsing rules. If consumers only accept a single format, this dependency should be explicitly documented, and then discussed to determine if it is reasonable. Contracts can expose unreasonable coupling, but they should not permanently protect all accidental dependencies.

Consumers need to distinguish between unauthenticated, unauthorized, non-existent, parameter error, and service failure scenarios, and ensure that the contract records accurately reflect the actual usage status and field values. Returning a unified successful empty object from the backend can lead to the interface incorrectly displaying “no order,” and the parser may also hide issues by default. To confirm the recovery prompt and retry rules, use real consumer code samples. It is important to verify how the page uses the error field, not just include it in test samples.

Paginated empty results and dependency failures are particularly prone to confusion. Contracts can express that an empty list still has a valid structure, while server failures have a stable category. Consumers should not treat these two as the same state. When time fields have explicit time zones, amounts have explicit units, and links have explicit primary domain names or relative baselines, it becomes easier to distinguish between them. Combining structural matching with manual semantic review can help identify cases where the type remains the same but the meaning changes.

The users in the test sample are combined with all orders, and the complete payload is not copied from production. The contract may be stored in a shared repository and public reports, but private fields are not automatically secured due to the “test data” name. The provider’s status must be prepared for use with controlled identities, and the testing should be limited to the test scope, without affecting real business. The contract testing tool also requires permissions and a budget.

Failure to publish access control should provide actionable results, such as identifying which consumer version relies on the amount number and which provider’s response has been changed to a string. When multiple consumers conflict, discuss compatibility and transition, without forcibly synchronizing all versions. A possible approach is to first add new fields, maintain existing fields, and then migrate consumers, and finally delete the old fields. Testing has proven compatibility at each stage, and the running logs confirm that the target version has been successfully deployed.

Finally, regularly remove contracts that are no longer supported. Maintaining old, unsupported dependencies can prevent the interface from evolving, while prematurely removing them can harm real clients. The lifespan of a contract depends on product support policies and actual deployment, not on whether the code is still available in the repository. A mature contract system should both prevent unwanted changes and allow for normal changes when supported by evidence.

Contract Changes: A Clear Discussion Material

Compare the old and new dependency lists to identify additions, deletions, and semantic changes. A field changing from a primitive type to a structured type, even if the type remains the same, constitutes a business disruption and requires a new field or version migration. The documentation provides information on units, time zones, and error handling semantics, while the test samples illustrate key boundary conditions. Do not rely solely on “all matcher passing” to replace manual semantic review.

Coverage is not calculated based on the number of response fields. Protecting three key fields and the failure branch can be more effective than locking the entire large object. Consumer unit tests, provider contract validation, real storage integration, and key end-to-end processes work together to pinpoint the cause of failure. The goal is to achieve evidence-based independent releases, rather than replicating all tests across every layer.

Extracting the True Dependencies Actually Consumed from a Bill Adapter

The billing page reads amountMinor, currency, and id. First, the test calls the actual adapter to map the response to a display model. If the adapter still incorrectly reads the total, the test will fail. The test only checks that the fields in the contract JSON cannot detect this error. For each dependency, a single sentence describes its purpose: the amount is used for calculation and display, the currency determines the unit, and the ID is used for resource linking. The minimum contract comes from real calls, not from arbitrarily deleting fields from a sample interface.

How does the adapter handle unknown states, and this is verified through real code? Adding new states in the backend could be a compatibility extension. If the frontend directly asserts that all external values are known, it will crash. One option is to retain “unknown” at the input boundary and display it explicitly, or to define a limited enumeration in the interface and require version changes when it is modified. It is important to first establish reasonable dependencies and not permanently protect a client’s overly strict assumptions.

The array sample should at least demonstrate the order and pagination preferences that consumers care about. Returning only one record prevents the detection of changes in sorting direction; the hasMore flag and the cursor are inconsistent, which could lead to users repeatedly requesting data. A small number of states create a readable interaction, avoiding the need to lock down thousands of real orders. All test data is synthetically generated, and contract storage and reports do not duplicate private billing information.

Provider status cannot be used as a workaround.

State preparation can establish a paid order or an unauthorized identity, but formal requests must go through a real handler, serialization, and error handling. If in test mode, the tool directly returns a contract sample, and the validation is performed by the tool itself, not the service. Whether the database is real depends on the validation target, but the response boundary must actually execute. There are also integrated evidence for transaction correctness and concurrency constraints, ensuring that the contract does not impersonate the entire storage.

The status data adheres to business constraints, preventing the insertion of incomplete, unusable “half-products” solely to match the response. Preparation and cleanup operations occur in separate, isolated scopes and cannot delete other test records. A fixed ID in the shared environment is easily modified by other sets, ensuring the repeatability of validation. The authentication sample uses controlled test identities, avoiding the need to disable all authentication checks for “interface compatibility.”

The meaning of failure states is equally important. Consumers should correctly interpret insufficient permissions, the absence of stable fields, and unavailable services. An empty array indicates a successful, but empty, result. The provider’s error messages can be improved, and a clear agreement should be established between the machine code and the data types. The public response should not include internal stack information, and the contract should not imply the creation of new private fields. Information minimization should still be subject to independent review.

Determining the Independent Release Order Based on Version Combinations

Consumer B relies on the new field, which Provider A does not yet have. Provider B adds a compatible field while retaining the old field. First, deploy and verify Provider B, then release Consumer B, and finally, remove the old field after the old consumer has stopped supporting it. The verification matrix records the specific build and environment, and cannot be used to derive that the current production provider has the necessary capabilities based on a successful development branch.

When rolling back a consumer, the provider continues to support legacy dependencies, which typically have valid combinations. If the provider has removed the old fields, the old consumer may no longer be rollable back. Access control requires maintaining the active version, not just the latest source code. Long-term offline support for external clients and mobile devices is more complex, and the central contract library does not automatically cover unknown consumers. Reporting on who is covered and who is not is essential to avoid false security.

There are specific reasons, deadlines, and risk responsibilities associated with manual overrides. While fields that cause unintended blocking can be reasonably modified, true damage cannot be resolved simply by eliminating all types of errors. Error reports indicating specific interactions, field versions, and consumer versions can help in selecting a compatible transition. A door control system with only red and green lights, without any action information, is easily circumvented. It should be improved for diagnosis rather than simply being turned off by default.

Semantic Transfer with Fixed Types Requires Additional Evidence

The amount is converted from yuan to cents but remains a “number,” while the date is converted from local time to UTC but remains a “string.” The link is converted from a standard article address to the root entry. Structural matching may be possible but can disrupt user tasks. Provide explicit examples and relationships for key units and time, and review the meaning of fields manually. Use clearer field names or version transitions when appropriate, and do not force misleading names to remain simply to avoid triggering contractual obligations.

The schema describes acceptable shapes, the consumer contract describes specific usage, business tests describe the results, and the end-to-end description describes the final task. Each layer has its own value, and duplicating the same large object across all layers does not increase semantic independence. By selecting a controlled sample amount, the page can display the expected amount and currency, allowing for cross-validation of the structure and units. Measurement is not fabricated research; the test sample indicates which relationship is being verified.

Intentionally Sabotaging Experiment Verification Access Control Capabilities

Convert the amount to a string; the provider’s validation should fail. New, irrelevant public fields should still pass. Change the error response to a successful empty object; the real consumer status test should fail. Unknown enums should be handled according to the approved strategy. The experiment should be performed in an isolated branch or sample service, without modifying the production interface. After retaining the evidence of failure, restore normal operation and then verify the validation relationships of the target deployment.

The addition of new fields ensures compatibility with the “not equal to” permission, preventing secret broadcasts. This requires a separate check by the information leakage sentinel. Before removing a consumer contract, it’s necessary to verify the support policies and deployment status. It’s not possible to assume that all clients have been upgraded simply because the repository branch has disappeared. The testing system also supports preventing real damage and allowing evidence-based evolution, which is more valuable from an engineering perspective than simply fixing old interfaces permanently.

Success Reports Should Focus on Dependencies, Not the Entire System

Explain which consumer codes are actually running, which provider versions are being validated, whether the state is isolated, and which business aspects still require other tests to prove. Unverified sandboxes should be marked as such and not considered passing. The contract guarantees independent, verifiable compatibility, but cannot guarantee that users will receive the product or that there will be no concurrency issues in the database. Clear guarantees make each layer of testing more trustworthy.

The contract release log should also specify the verification environment and build identity, and should not only save the latest successful marker, which would overwrite everything. After the provider fixes the issue, the current build should be re-verified, and the failed samples should also be retained for necessary diagnostics. When the consumer version is no longer supported, there should be a clear reason, and the verification records should not be automatically applied to new runs simply because they have the same name.

Intentionally Sabotage During Acceptance

  1. Temporarily change the amount type incorrectly; the provider’s verification should fail.
  2. Add an irrelevant field; the verification should still pass.
  3. Add a new, unknown order status; the consumer should display it according to the agreed-upon behavior instead of crashing.
  4. Confirm that the target deployment version has corresponding verification records.

The value of contract testing isn’t just generating more green reports; it’s about enabling the team to understand the boundaries of their dependencies when releasing independently. If the testing only replicates documents without calling real consumer code, those boundaries remain unverified.

References