Testing an API without a live database: what a fixture proves and what it does not

Separate API response checks from SQL: independent expectations, a stubbed reader and a distinct MySQL 8.4/InnoDB check in a guarded disposable schema.

A small controlled sample and a wider collection suggest the limits of fixture-based testing.
A small controlled sample and a wider collection suggest the limits of fixture-based testing.

Imagine an API test that always returns two published notes. It checks status 200, the required fields and the order of the cards. A change to the SQL query lets drafts into the result, yet the test stays green: its two notes never came from the database.

That test can still be useful. The mistake begins when its result is presented as evidence that the entire read operation is correct. For tests to support decisions, we need to see where they exercise real code and where they receive a predetermined answer.

Let us examine this boundary with an independent notes catalogue in the same Symfony Demo. The separate test layers are the PHP model, a kernel with a stub and the real MySQL 8.4 reader through native PDO, with and without the kernel. Independent literal JSON expectations are retained: the JSON shown explains the contract rather than replacing a check of the real reader's response.

Start with two specific operations

Our catalogue supports reading a list and reading one note. The list has a fixed page size of two items. The detail response contains one available note or a defined refusal. Creating, editing and deleting notes are outside this contract.

The list contract specifies locale, page, total and items. Each item has an id, a title and a nonnegative integer readingSeconds. An empty list remains an array, []; a read outage does not become a successful empty response. Data belongs to two fictional scopes, north and south.

The scope comes from a trusted access context. It is not a parameter a client can use to redefine its permissions. The local exercise supplies credential state and grants explicitly. This allows it to check the model's admission rule, but it does not implement validation of a real token.

Here is the expected first page of the English selection in north:

{
  "locale": "en",
  "page": 1,
  "total": 3,
  "items": [
    {"id": "note-21", "title": "Calm Water", "readingSeconds": 60},
    {"id": "note-22", "title": "Field Notes", "readingSeconds": 61}
  ]
}

The third note belongs on page two. On page three, items is empty while total is still three. The number of items on the current page and the size of the whole selection answer different questions.

Name the point where the fixture enters

Here, a fixture means prepared state or a value used for a repeatable check. It might be a JSON response, rows in a test database or an object returned by a stub. The word alone does not describe the path exercised.

In our example, ScriptedNotes replaces the lower reader. It receives the scope, locale and page number or ID, compares them with a prerecorded call and returns a specified projection. It does not sort rows, execute SQL or decide which notes are published.

Above it sits the real code of the exercise, ContractApi: it checks allowed parameters, applies the permission model, builds a response and selects public fields. A future successful run can therefore establish how these classes behave on the specified inputs. It cannot establish how the replaced component behaves.

Symfony distinguishes unit, integration and application tests. For our purpose, it helps to add a short description of the actual boundary: “classes and JSON without the kernel”, “kernel with a substituted reader” or “kernel with the real reader and a test database”.

Test arrangement What the test may exercise What remains outside it
Local classes with a stub Parameter forwarding, field selection, model rules Routes, firewall, serializer, SQL
Application with a substituted lower reader Real routes, middleware, normalization and errors, if retained The replaced reader's query and data
Application with a disposable database The previous path, the real read adapter, schema and synthetic rows Production data, load and environment

The table describes possible scope. Booting a kernel does not by itself guarantee that a particular service remains real: the test configuration determines that.

Build a matrix rather than one successful request

The two operations have 36 prepared input scenarios. They cover the first, subsequent and empty pages, different locales and scopes, available and missing notes, invalid parameters and unavailable reads. Both operations have cases for missing or rejected credentials, missing permission and permission for a different action.

This matrix is complete only relative to the small declared contract and the chosen input classes. It does not mean an exhaustive search of every possible string, header combination or future product operation.

Each case records not just the status and body but also the exact calls to the lower reader. A refusal of access must produce zero calls. If code reads the data first and returns 403 afterwards, checking only the status misses the wrong order. In the teaching model, an incorrect scope or locale also violates the expected call.

Invalid page inputs include 0, +1, 1.0, an array, 101, null and 01. The exercise accepts canonical strings from 1 to 100; an omitted page means the first page. This is the parser's local agreement, not a universal rule for APIs. Its purpose is to prevent ambiguous input from acquiring an accidental meaning through type coercion.

An expectation must survive an implementation mistake

The source projections and expected public responses are written separately. A projection deliberately contains internalMemo with a fictional private marker. The public response must contain exactly the three permitted note fields. Returning the whole array instead of selecting fields explicitly would introduce an extra key that exact comparison should detect.

Do not build the expected document with the same mapper being tested. If one function mistakenly produces milliseconds instead of seconds for both the result and its reference, the two sides will agree. Our agreement fixes note-21 at exactly 60 seconds; 60000 must be rejected regardless of how neatly the JSON is encoded.

The comparison preserves types and array element order while ignoring object property order. JSON arrays contain ordered elements, so swapping two cards may change the contract. Nor are [] and {} two ways to express the same empty collection.

Precision belongs wherever there is a promise. A real HTTP response may have dynamic headers or values. For those, explicitly choose a check of format, relationship or an allowed set. Removing every inconvenient field before comparison would remove part of the contract itself.

Check whether the test notices an intentional fault

The exercise includes 11 separate documents for checking the comparator. Nine contain meaningful violations: an incorrect total type or value, another locale, reordered or missing items, a private field, a wrong unit, an incorrect status or an object in place of an empty array. Two preserve meaning: reordered object keys and different casing in a header name.

These cases ask whether the comparison tool rejects the required differences and accepts the agreed insignificant changes. They do not replace running a mutated application: here, the completed documents are changed. The description of the result needs to retain that distinction.

API Platform provides separate JSON and JSON Schema assertions. A schema describes a document's shape well. The requirement “these exact two notes, in this order, in seconds” also needs domain expectations. A valid shape does not establish where a value came from.

Changes to fixtures also need an explanation

A few weeks later, a note might gain an optional description. Exact comparison with the old document will report a difference. That does not mean we must either forbid the new field or automatically rewrite every reference. First return to the promise made to the client: are unknown fields allowed, have existing meanings changed, and does the old consumer still work?

Our exercise deliberately has a closed response: three note fields and a known envelope. After an agreed change to that rule, the reference can be updated, together with an explanation of the new expectation. But if the new field is an internal memo, updating the snapshot merely teaches the test to accept a leak. An “accept all changes” button cannot distinguish those situations.

The dataset also needs review. Two notes with different ranks will not expose the absence of a second sort key. English records alone will not raise a question about locale. Each unusual row in our dataset therefore has a reason: a tied rank, an unpublished state, another scope or another language variant. Removing that row removes a specific question for the implementation.

A useful order for changing a test is to describe the new behavior first, update the data and expectations next, and then check the implementation. This does not prohibit fixture updates. It preserves their independence from whatever the code happens to produce at the moment.

Restore the application's actual path

The checks were added to the same Symfony application without another skeleton, Kernel or Composer root. Existing routes, configuration and earlier scenarios were preserved. Root autoload loads the example’s individual classes.

In the test environment, real HttpKernel routing, controller and HttpFoundation JsonResponse encoding use a replaceable read port. Trusted TestAccess supplies synthetic credential state, grants and scope from test configuration, never query parameters; outside test it rejects configuration and initially denies access. This does not test Bearer validation or a production firewall. Symfony supports replacing dependencies in its test container.

Thirty-six BrowserKit parameterized kernel cases checked exact statuses, JSON types/values, headers and call logs. Access refusal did not call the lower reader. L16 injects typed page: null into an in-process Request; it does not claim that a URL or query string encodes JSON null. The real HttpFoundation JsonResponse used here is not SerializerInterface, and BrowserKit kernel calls are not external HTTP transport.

This kernel-with-stub layer checks wiring and presentation, but ScriptedNotes executes no SQL predicates or sorting. The next layer therefore exercised the real reader separately, rather than inferring database correctness from a completed projection.

A separate disposable database for the reader

The prepared dataset contains seven synthetic rows. In north/en, there are three published notes, one draft and one scheduled note. Two published notes have the same published_rank. Another row provides a Ukrainian translation of note-21; the final row belongs to south/en.

For this exercise, the query must select the exact scope, the exact locale and the published state, ordering first by published_rank and then by id. The rank is a synthetic sorting key; it does not model a publication calendar. PostgreSQL's documentation explains why LIMIT needs an unambiguous order when a predictable subset is required.

The stub may have returned note-21, note-22 simply because that order was written in JSON. The real reader must derive it from rows. Loading those rows in reverse order is useful: the expected first page should remain unchanged. A draft with a smaller rank must not appear before the permitted notes.

The ten literal parity cases check PublicNotes::page/one results without the kernel: independent items/total/item or null expectations are compared before the API mapper. The same expectations apply through the kernel with the real MySQL reader. Forward and reverse insertion order check that the result remains unchanged; they do not add new input classes. The important invariants are integer readingSeconds, exact scope, locale and published predicates, and published_rank ASC, id ASC ordering.

The test database is now a disposable schema on actual MySQL 8.4, created by the shared App\Infrastructure\MysqlLab helper under the guarded test fixture. A separate migrator explicitly prepares the InnoDB tables before the transaction that loads the seven synthetic rows; the runtime connection performs DML only and cannot execute CREATE, ALTER or DROP. Separate native PDO connections share the test schema rather than using a production DSN. Fixture setup, not the runtime reader, introduces the missing-table fault; the expected failure is an explicit 503 directly and through the kernel, not a successful empty response. This checks a PDO adapter and schema, not the correctness of ORM migrations. Symfony recommends a separate test database.

Seven rows do not represent the product's entire database

This example specifically checks MySQL 8.4/InnoDB through PDO_MYSQL, not SQL portability between engines. String identities use VARCHAR with utf8mb4_0900_bin comparison, while titles and bodies use LONGTEXT; the schema uses MySQL constraints, including foreign keys and CHECK constraints. DDL runs separately: it can cause an implicit commit in MySQL, so initialization is not an atomic schema upgrade. Nor does it automatically copy data from an old SQLite database. A compatible data access interface does not remove storage differences.

We also need to decide which mechanisms are actually involved. A DBAL query does not establish that ORM mappings are correct. Reading through a fresh connection does not test a long-lived identity map. An absence of problems on seven rows establishes neither performance nor locking behavior, nor whether historical data satisfies new constraints.

For Doctrine, testing a repository through a real connection exercises a boundary that a repository mock bypasses. Even that run has a particular schema, dataset and scenario. Widen the conclusion as the experiment itself becomes broader.

Leave a result that can guide the next change

To check the real reader, first prepare the Demo's shared guarded MySQL fixture and run database checks through fixtures/mysql_labs/run.sh. The wrapper selects the test server, while MysqlLab creates a disposable schema and runs the migrator separately. PHP syntax checks or a model run with a stub are not sufficient to check SQL.

Count the layers separately: the PHP model contains 36 operation cases and 11 comparator cases, while the kernel with a stub has 36 cases. The MySQL reader checks use ten independent expectations with two insertion orders, without the kernel and through it; a read outage must produce 503 at both levels. These are different test boundaries, not a single accumulated proof of API correctness. The current Demo's effective PHP minimum is 8.4.1. These checks do not establish PostgreSQL behavior, ORM identity maps, concurrency, production parity or a complete API audit.

After an actual run, write a short sentence that matches the evidence precisely: which classes or application path ran, what was substituted, which data was used and what result was observed. The next change then has a clear test. Replacing the serializer needs the real normalization path; changing SQL needs the real reader; changing the response shape needs client expectations.

A good fixture makes a small part of behavior repeatable. It becomes more valuable when the next untested boundary and a concrete way to test it are visible alongside it.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/FixtureBoundaryLab
  1. Symfony Core Entity or DTO: which data should a page receive from storage?
  2. API An API response is not an Entity: designing an article card
  3. Symfony Core Testing a useful feature: from one rule to an HTTP journey

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article