What an AI Integration Test Should Actually Assert

What an AI Integration Test Should Actually Assert

Published on

1

views

This article explains how to write robust integration tests for AI features by shifting focus from model intelligence to application reliability. It outlines five essential assertion categories: contract validation, negative schema tests, failure fallbacks, audit persistence, and cost limits. By asserting behavioral boundaries rather than golden output snapshots, engineering teams can ensure predictable performance and protect production systems.

I once inherited a test suite that claimed 94 % coverage on an AI feature. Every test passed. The feature still broke in production the first time a user pasted a slightly longer message. The tests had been asserting the wrong things.

They checked that the HTTP status was 200. They checked that a JSON object came back. They even checked that three specific keys existed. What they never checked was whether the system behaved correctly when the model returned something unexpected, incomplete, or expensive. That is the gap most AI integration tests quietly leave open.

This post is the checklist I now use before I call an AI feature “tested.”

The Core Problem With Most AI Tests

Low-angle shot of a backend engineer reviewing a failed AI integration test on a laptop screen in a modern workspace.

Traditional integration tests assume the dependency is deterministic. You send input X, you expect output Y. Large language models break that assumption. The same prompt can produce different token counts, slightly different JSON shapes, or occasional schema violations even when you request structured output.

If your tests only assert the happy path, you are not testing the feature. You are testing the demo.

An AI integration test should answer a different question:

When the model misbehaves in realistic ways, does the application still protect the user, the data, and the bill?

That single shift changes what you write.

What I Actually Assert

I group assertions into five categories. Every meaningful AI integration test should hit most of them.

1. Contract assertions (the shape we promised)

These are the closest thing to classic tests. Given a valid request, the endpoint must return a response that matches our public contract—not the model’s raw output.

I assert:

  • Required fields are present and correctly typed

  • Optional fields are either present with the right type or explicitly null/absent according to the schema

  • No extra fields leak from the model into the public API

  • Error responses use our standard error envelope, not a raw model error

The test should never pass simply because “something JSON-shaped came back.”

2. Validation and rejection assertions

This is where most suites are thin. I deliberately feed the system responses that a real model might produce:

  • Missing required fields

  • Wrong types (string instead of number, array instead of object)

  • Values outside agreed ranges

  • Extra unexpected keys

  • Truncated or malformed JSON

The application must reject these before they reach the database or the user interface. A test that only ever sends clean model output is not an integration test; it is a unit test of the happy path.

3. Failure-mode and fallback assertions

What does the product actually do when the model is slow, rate-limited, or returns garbage?

I assert:

  • Timeouts produce a controlled fallback, not a hanging request

  • Schema validation failures trigger the documented recovery path (retry, human queue, or graceful degradation)

  • The user never sees a stack trace or a raw model error message

  • Partial or low-confidence results are either discarded or clearly marked

If the only “error test” is “mock a 500 and check we return 500,” the suite is incomplete.

4. Side-effect and persistence assertions

Every AI call that matters should leave a trace. I check that:

  • A task or audit record is written with the request ID, model version, token counts, and validation status

  • Failed calls are recorded as failures, not silently dropped

  • Sensitive raw model output is either redacted or stored under the correct access controls

  • Retries do not create duplicate business records

Without these checks you cannot debug production incidents and you cannot audit cost.

5. Cost and resource assertions (the ones people skip)

I do not assert exact dollar amounts—pricing changes. I do assert boundaries that protect the system:

  • A single request cannot exceed a configured token ceiling

  • Retry logic has a hard upper bound

  • Bulk or expensive paths require explicit flags or higher authentication

  • Logging captures enough information to reconstruct later cost analysis

These assertions turn “we hope it stays cheap” into something the test suite can enforce.

A Minimal but Useful Test Structure

Here is the pattern I reach for with pytest and a FastAPI service.

Python

async def test_summary_endpoint_rejects_invalid_model_output(client, mock_model):
    # Arrange: force the model to return something schema-invalid
    mock_model.return_value = {"summary": 12345}  # wrong type

    # Act
    response = await client.post("/v1/summaries", json={"text": "Short ticket"})

    # Assert – contract
    assert response.status_code == 422  # or our chosen validation status

    # Assert – no side effects on failure
    assert await db.count_successful_summaries() == 0

    # Assert – failure was recorded
    failure = await db.get_latest_failure()
    assert failure.reason == "schema_validation"
    assert failure.model_version is not None

Notice what is missing: I never assert that the model produced a “good” summary. That is not a stable property. I assert that the application behaved correctly around the model.

The Personal Mistake That Taught Me This

Early on I wrote a beautiful test that compared the model’s output against a golden JSON file. It passed for weeks. Then OpenAI (or whoever ships the next GPT-6.1 Sol revision) changed the default verbosity of structured outputs. Every golden file broke overnight. We spent a day updating snapshots instead of shipping.

Now I treat golden-file tests as a code smell for anything that touches the model. Prefer behavioral assertions over content snapshots.

What I Still Do Not Assert

  • Exact natural-language wording

  • That the model’s answer is factually correct

  • That two consecutive calls produce identical token counts

  • That the model will always stay within a latency budget under load (that belongs in performance tests)

Those properties are either unstable or belong to a different layer of testing.

Practical Checklist Before You Call the Suite “Done”

  • At least one test forces a schema violation and checks rejection

  • At least one test forces a timeout or rate-limit response and checks the fallback

  • Persistence of both success and failure paths is verified

  • Token or cost ceilings are enforced in at least one test

  • The public API contract is asserted independently of the raw model shape

  • No test requires the live model to be “smart” in order to pass

If you can check most of those boxes, you have something far more useful than a 94 % coverage number that only exercises the demo path.

Wide-angle shot of an engineer reviewing broken snapshot test logs after a model version update in a dim room.

Closing Thought

An AI integration test is not a claim that the model is reliable. It is a claim that the application remains reliable when the model is not. That is a much more valuable—and much more testable—property.

Write the tests that protect the user and the invoice. Leave the poetry evaluation to humans.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

The Demo Worked Until the Input Was Slightly Different

The Demo Worked Until the Input Was Slightly Different

This article explores why early AI features often fail when encountering real-world user inputs that differ from polished demo examples. It covers common edge cases like length limits, structural variations, and empty responses, providing practical boundary-testing strategies, rigorous error-handling methods, and robust status tracking to ensure your AI application remains reliable in production.

0