Consumer contract tests: catch a break before upgrading the site
One unchanged consumer suite checks two library versions. Explore a behavioral regression, exact artifacts, and the difference between contract rejection and execution errors.
A new library version installs without conflicts. Its method has the same name, accepts the same arguments, and returns a string or null. Yet an English card with no translation suddenly displays a Ukrainian title. The call is valid according to the types. The site, however, has received different behavior.
It is useful to discover this before upgrading the working application. That requires a test owned by the consumer, expressing its expectations independently of the library implementation. One unchanged suite checks both the previous version and the candidate. When an expectation is violated, the report should show the specific difference rather than just a failed installation process.
We examine an executed independent teaching example with two local versions of a fictional library. The matrix ran on PHP 8.5.12 and Composer 2.9.2 in two temporary Composer consumers, with no additional Symfony applications. The unchanged ten cases accepted version 1.0.0 and detected exactly the planned behavioral regression in 1.0.1.
What the page has actually been promised
Imagine a reading page that retrieves a card title by key and exact language. It uses this public method:
public function read(string $key, string $locale): ?string
The PHP declaration specifies argument types and allows a string or null as the response. It does not explain when to return null, whether language fallback is permitted, or how to handle an unpublished card. Keep this distinction between a type and an agreement in view; the declaration itself is covered by the PHP documentation.
The consumer defines narrow rules. The exact values uk, ru, and en are supported. An unknown key, a hidden card, or a missing translation returns null. A blank key or unsupported language is rejected with InvalidArgumentException. A stored title containing only spaces is invalid data and produces UnexpectedValueException.
These are the rules of the synthetic exercise. Another product may deliberately choose fallback, but should include it explicitly in its own contract. The problem here is an unagreed change to the promise, not a universal prohibition on language fallback.
The user of the result writes the expectations
The provider needs its own algorithm tests. The consumer needs an answer to a different question: does the behavior its page relies on remain intact? If both suites calculate expected results using the same library helper, a bug in that helper may change both the result and the criterion used to judge it.
In this exercise, expectations are written literally in the consumer suite. The atlas card has three titles: Річкова мапа, Речная карта, and River chart. The ferry card has only the Ukrainian title Переправа. The English page should receive the absence of a translation, not replacement text chosen by the provider on its own.
| Public call | Consumer expectation | Reason |
|---|---|---|
read('atlas', 'en') |
River chart |
The exact translation exists |
read('ferry', 'en') |
null |
No English translation exists |
read('absent', 'uk') |
null |
The card does not exist |
read('unreleased', 'en') |
null |
The card is unpublished |
read('atlas', 'pl') |
InvalidArgumentException |
The language is outside the contract |
The suite does not read provider source, access private properties, or check the name of an internal helper. It uses the public constructor to supply synthetic data and calls read(). The constructor accepting this data is itself part of the teaching API, rather than a hidden way to change object state.
It is useful to record separately what the consumer does not promise to test. This page does not depend on the number of internal methods, the name of an intermediate array, or how cards are stored inside the object. A test fixing those details would obstruct a compatible refactoring. The difference between an exact title and a missing translation, however, directly determines what the reader will see.
The literal strings in our table are controlled synthetic data, not a copy of a changing production catalog. A real test using mutable data first needs a reproducible state or its own fixture. Otherwise, an author's title edit may look like a library regression. The contract suite should remain sensitive to changes in the behavior being consumed without demanding that all product content remain unchanged.
One change the types will not catch
The first local version is numbered 1.0.0 and returns a title only for the requested language. Candidate 1.0.1 deliberately adds Ukrainian fallback when the requested title is missing. The class name, constructor, method signature, and return type remain unchanged.
The candidate number is part of the controlled mistake. It does not claim that this change has been correctly classified as a patch release. The version string alone does not prove behavioral compatibility.
Both installations run the same consumer-suite case:
$cases[] = $this->value('missing_translation', null, fn () => $catalog->read('ferry', 'en'));
The value() method invokes the public operation and compares the expected and actual values using ===. It does not rely on PHP's disableable assert() mechanism or convert an empty string into null. An unexpected exception is recorded separately from a mismatched value.
Ten cases have been prepared: three available translations, a missing translation, an unknown key, an unpublished card, a blank key, an unsupported language, an invalid stored title, and a repeated read. Two identical results from repeated calls check that particular observed scenario; they do not prove the general absence of every possible side effect.
Testing the package without maintaining two sites
For each version, the runner prepares a separate temporary Composer installation. It contains a minimal consumer manifest, exactly one selected version of the teaching provider, and its autoloader. This does not require two permanent Symfony applications.
The providers come from two fixed synthetic source files. Their temporary package manifests are generated during the experiment. The name workshop/card-labels belongs only to this local exercise; Packagist access for it is disabled. The matrix does not publish a package or update the working site's dependencies.
Local artifacts use a Composer path repository with symlink: false. This copies the installed code into each consumer. Otherwise, changing a shared directory could silently change what both installations are testing. Copying alone does not make the source immutable: the runner therefore also checks the installed file's content against the selected artifact.
The consumer suite is copied once before both runs. Its checksum must remain unchanged. This is a straightforward condition for a fair comparison: do not adjust the expectations after the candidate violates them.
Record what was actually installed
After choosing a version, reading require in the manifest is insufficient. Preserve the actual composer.lock, installation result, and version visible to the executing code. Composer provides InstalledVersions for runtime inspection; the exercise checks the exact selected local package version.
The initial run creates a lock with composer update in a new temporary directory. Reproducing the saved dependency set requires composer install with that lock. The Composer documentation explains the difference between selecting dependencies and reproducing them. The local provider sources must also remain available: a lock referencing a deleted directory cannot restore its bytes.
The runner refuses an existing output directory or symbolic link. Commands are executed as argument lists, without joining shell command strings. The report retains each process's stdout, stderr, and exit code. If Composer fails to install the dependency, behavioral verification has not started.
The package itself requires PHP 8.4 or later. Compatibility of the additional Symfony stage is determined by the application's current dependencies. The teaching library's minimum is no reason to downgrade PHP, Symfony, or PHPUnit in an existing project.
The negative control must fail for the intended reason
The actual matrix confirmed the predefined criteria below. Version 1.0.0 produced 10 passed, 0 failed/errors, exit 0. Version 1.0.1 produced 9 passed and one expected failure, missing_translation: expected null, actual Переправа; errors 0, exit 1. These are 20 external consumer case executions, not 20 PHPUnit tests. The third table row defines rejection for environment errors; none occurred in this run.
| Installed provider | Expectation across ten cases | Consumer-process exit code |
|---|---|---|
1.0.0 |
Every case matches the contract | 0 |
1.0.1 with deliberate fallback |
Only missing_translation is violated |
1 |
| Unknown class, broken installation, or unexpected exception | The experiment has not demonstrated the intended regression | 2 or a preparation failure |
Exit code 1 is insufficient. The outer runner checks the complete case list, the successful-check count, the absence of execution errors, and the exact violated case ID. It also checks the installed version, provider content, and unchanged suite. A different failing case does not count as a successful rehearsal.
When the controlled defect is detected, the experimental protocol may complete successfully. The candidate itself remains rejected. These are answers to different questions: did the check work, and is the proposed library compatible?
The same distinction matters in ordinary PHPUnit: its runner documentation distinguishes a failed assertion from a test execution error. The teaching matrix uses a small separate runner, so its exit codes and JSON format are explicitly defined rather than presented as PHPUnit's format.
Add one check to the existing Symfony application
The independent matrix tests the library through its autoloader. It does not test a particular site's container. An additional command, app:consumer-contract-demo, is prepared for that purpose. It receives the consumer suite through constructor injection and returns the report.
The command and kernel test are added to the same teaching application. They do not create another Kernel, a skeleton copy, or a separate permanent vendor directory. New classes occupy their own namespace; existing routes, configuration, and earlier scenarios are preserved.
The kernel test expects compatible version 1.0.0, boots the real container, finds the command, and checks its report. Symfony documents CommandTester as a tool for testing commands. This check can expose service-wiring problems that a direct class call would miss. It also requires actual execution: the test file alone does not establish that the container works.
The one existing Demo retains compatible library 1.0.0: its lock uses the relative path fixtures/consumer-contract-provider, and symlink: false makes Composer copy it. Installed source bytes match the retained fixture. PHP lint and container lint exited 0. The command accepted 10 of 10 cases; a separate KernelTestCase passed with 1 test / 8 assertions. These integration checks are counted separately from the 20 external cases. The installed Symfony/PHPUnit dependencies require an effective PHP minimum of 8.4.1; the actual run used PHP 8.5.12.
Use the rejection to make an upgrade decision
When an unchanged expectation is violated, first determine whether that expectation still applies. If the site needs the exact language, accidental fallback should be corrected in the provider. If the product now deliberately adopts fallback, that is a separate change to requirements, the contract, and consumer behavior. It should not be hidden inside a dependency upgrade.
A consumer-owned suite is retained with its owner and revision. A provider can run accepted checks from known consumers before release; a consumer can run them before accepting a candidate. Both need an exact pairing: which expectation set checked which artifact?
Specialized tools exist for HTTP and messages. For example, Pact describes separate consumer tests and provider verification based on interaction contracts. This exercise checks a local PHP package without HTTP, a mock server, or a Pact Broker. The shared idea is independent consumer expectations; the verification mechanism differs.
Ten cases do not cover every input, concurrency, performance, or other sites. They make one concrete dependency visible and testable. An upgrade decision can then rest on behavior the product actually uses, with a clear reason for rejection before the working environment changes.