Testing AI Features: Unit Tests for Non-Deterministic Outputs

Testing AI features means testing in layers: mocked unit tests, golden datasets, and evaluations that score properties instead of exact text. The full approach.

By Galactic News Editorial · Published 2026-11-22T20:08:48+00:00 · Updated 2026-11-22T20:08:48+00:00

Testing AI features unit tests for non-deterministic outputs

Testing AI features starts with one uncomfortable fact: you cannot unit-test a language model the way you test a normal function. The same prompt returns different wording on every call. That does not mean AI features are untestable. It means you test different things: the deterministic code around the model, the properties of its output, and the quality of its answers at scale.

This guide shows how to write unit tests for non-deterministic outputs, layer by layer, without brittle string assertions.

Why exact-match assertions fail

A traditional unit test follows a simple contract: given input X, expect output Y. LLM output breaks that contract three ways. First, non-determinism: with temperature above zero, identical input can produce different output on every call. Second, semantics instead of syntax: "You have 14 days" and "The return window is two weeks" mean the same thing but share almost no characters. Third, the ground moves: model updates, API version changes, and prompt edits can all change behavior without any change to your application code.

Setting temperature to zero reduces variance and is a sensible default for test runs. It is not a guarantee. No major provider guarantees reproducible tokens, because requests are batched and floating-point accumulation differs between batches. A suite built on exact strings goes red on Tuesday and green on Wednesday, and teams learn to ignore it within a sprint.

The useful move is to split the code at the model boundary. Prompt assembly, retry logic, output parsing, tool dispatch, and every branch that consumes the parsed result are ordinary deterministic functions. They deserve ordinary unit tests. Only the single call that crosses into the model needs an evaluation.

Testing AI features non-deterministic outputs: the four layers

The testing pyramid for AI applications has four layers. Each layer verifies something different, and each catches a different class of failure.

LayerWhat it verifiesDeterministic?Needs an API key?Speed
Unit tests with mocked modelPrompt assembly, parsing, routing, error handling, retriesYesNoMilliseconds
Fixture and golden-dataset testsSchema contract, edge cases, known regressionsMostlyNo, replay recorded responsesFast
Evaluation testsOutput quality, tone, factual alignmentNoUsually yesSlow
Regression suite in CIWhether a prompt or model change broke behaviorMixedDepends on the mixVaries

Most of your tests should live in the bottom two layers. They are fast, free, and stable. The expensive, non-deterministic evaluation layer runs on a schedule or on pull requests that touch prompts and models.

Layer 1: unit tests with a mocked model

Mock the model client for every test that does not need a real response. This covers prompt template substitution, input parsing, output routing, and service logic. These tests run in milliseconds and cost nothing.

Test prompt construction directly. Build the prompt from a template and an input, then assert that the required values appear in it and that the prompt stays under the length limit. A template that drops a variable silently is a bug that no amount of model testing will catch.

Test service logic with a mocked client. Return a fixed response from the mock, then assert that your code routes it correctly, parses it into the expected structure, and handles the error paths. Test the boundaries, not the model: does the code accept any valid category, reject an empty string, and fall back when confidence is low?

Test error handling and resilience. AI services fail. Rate limits hit. Networks drop. Write tests for timeout handling, retry behavior, and the fallback path. Mock a timeout and assert that the code returns a degraded result instead of crashing.

Test confidence thresholds. If your system uses confidence scores, test the logic that acts on them. Mock a low-confidence response and assert that the fallback triggers. You are testing your handling logic, not the model.

Layer 2: golden datasets and recorded fixtures

A golden set is a version-controlled file of real inputs paired with the properties their outputs must satisfy. Every production bug you fix in an AI feature becomes one more row in that file. The set grows with the product, and it is the asset your regression suite protects.

Record real responses as fixtures. Run the model once, save the response, and replay it in tests. Fixture tests check the schema contract: does the recorded output parse, does it contain the required fields, and does your code handle the edge cases in it? They do not check whether the model is good. They check whether your code survives what the model returns.

Keep fixtures as JSON or JSONL. Each case should carry the input, the recorded output, and the assertions that must hold. Review fixtures when you change a prompt or a model, because a fixture recorded against the old behavior can hide a new failure.

Layer 3: evaluation tests that score properties

An evaluation runs a prompt against fixed inputs and scores the output on properties rather than exact text. The properties depend on the feature, but the pattern is the same. First, run deterministic assertions: schema validation, required substrings, forbidden strings, and numeric ranges. These catch most regressions, run in milliseconds, and cost nothing. Run them before any judge call.

Then score quality with an LLM-as-judge. A second model scores the first model's output against a written rubric. The judge is only trustworthy when its model ID is pinned, its rubric asks binary questions, and its verdicts have been compared against human labels. A judge that has never been calibrated is an opinion, not a test.

Gate on regression, not perfection. Fail the build when the pass rate drops below a baseline committed to the repository. Treat raising that baseline as a reviewed commit. A gate that demands a perfect score will be disabled the first time it blocks a release.

Testing RAG retrieval separately from generation

When your feature retrieves documents and then generates an answer, test the two halves separately. Retrieval tests check whether the right chunks came back and whether they ranked well. Generation tests check whether the answer stayed grounded in what was retrieved.

This split matters because the fixes are different. A retrieval failure means the embedding, the chunk size, or the top-K setting is wrong. A generation failure means the prompt, the temperature, or the model choice is wrong. An end-to-end test cannot tell you which half broke.

Test tool calls the same way. When the model must choose a tool and format its arguments, test the selection and the argument parsing with mocked responses. Then test the real selection with a small evaluation set that covers each tool and the common mistakes.

Putting the layers into CI

Wire the layers into your pipeline by cost and speed. Unit tests with mocked models run on every commit. Fixture and golden-dataset tests run on every pull request. Evaluation tests run on pull requests that touch prompts, models, or retrieval, and on a schedule for everything else.

Tag the expensive tests so they can run separately. Integration tests that call a real model need an API key and real money, so they should not run on every commit. A nightly evaluation run catches drift without slowing down the team.

Keep the evaluation cost visible. Track how many model calls each run makes and what they cost. A suite that grows quietly into hundreds of judge calls per run will be cut the first time someone sees the bill. A small, focused evaluation set that runs fast is a suite that survives.

Common mistakes

The first mistake is not testing at all, on the reasoning that the output changes. The output changes, but the code around it does not, and the properties of a correct answer do not either.

The second mistake is asserting on exact strings. The test breaks every time the model rephrases, and the team stops trusting the suite.

The third mistake is testing prompt quality with a mocked model. A mock cannot tell you whether the model does the right thing. Prompt quality needs a real model, a golden set, and a judge.

The fourth mistake is running evaluations without a baseline. A score with no baseline is a number with no meaning. Commit the baseline, and fail the build only when it drops.

Bottom line

Testing AI features means testing in layers. Mock the model for deterministic logic: prompt assembly, parsing, routing, retries, and error handling. Replay recorded fixtures and a golden dataset for the integration path. Score output quality with evaluation tests that assert on properties, not exact text. Gate CI on regression against a committed baseline. The model is non-deterministic, but your tests do not have to be. Split the code at the model boundary, and every part of the feature becomes testable.