🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Testing LLM Applications: Units, Regression, Quality

LLMOps in ProductionLLM Testing StrategiesđŸŸĸ Free Lesson

Why assertion-style testing breaks down

Traditional unit tests assert equality: call the function, compare to the expected value, fail on mismatch. Point that habit at a language model and two problems appear immediately. The same prompt can legitimately produce different wordings on successive calls, so exact-match assertions fail even when behaviour is correct. And the behaviours you actually care about — faithfulness to context, appropriate tone, correct refusal — are graded qualities rather than exact outputs, so equality is the wrong relationship to test at all.

The discipline that replaces it has three moves. First, push as much logic as possible out of the model's hands: rendering, variable substitution, schema conformance, token budgets, and routing decisions are all deterministic code and should be tested exactly like any other code, with zero model calls. Second, where the model is genuinely involved, test properties rather than strings: does the response contain the required fields, fall within a length band, avoid forbidden content, and stay within a similarity envelope of a recorded baseline? Third, reserve a small number of expensive, model-in-the-loop checks for the qualities that only reveal themselves against real inference, and run those on a schedule rather than on every commit.

The payoff is a suite that runs in seconds for most changes, does not flake when a provider updates its sampling, and still catches the regressions that matter — a template variable that stopped substituting, a format that drifted, a quality score that slipped below the floor.

The testing pyramid for LLM applications

At the base sit prompt unit tests: rendering, variable coverage, token counts, and JSON schema validation. They are fast, free, and cover the majority of historical production bugs. The middle layer is integration tests with a mocked model: your orchestration code, tool routing, and parsing logic run end-to-end against recorded or synthetic responses, with no network dependency and no cost. The top layer is model-in-the-loop evaluation: real prompts against a real model, scored by rules or a judge, executed nightly or on pull requests that touch prompts.

Each layer catches different defects. Prompt unit tests catch wording and budget mistakes. Integration tests catch broken parsing when a provider changes its response envelope, and broken tool-selection logic. Model-in-the-loop tests catch quality regressions that no deterministic check can see. Skipping the middle layer is the most common structural error: teams test prompts and then trust that the orchestration around them works, right up until a JSON response arrives wrapped in markdown fences and the parser dies in production.

LayerWhat runsCost per runTypical trigger
Prompt unitRendering, budgets, schemasFreeEvery commit
Integration (mocked)Orchestration, parsing, toolsFreeEvery pull request
Model-in-the-loopReal inference, scoredMeteredNightly, prompt changes
AdversarialAttacks, edge casesMeteredWeekly or on policy change
LoadConcurrency, rate limitsMeteredBefore releases

Deterministic prompt unit tests

A prompt test renders the template with known variables and asserts on the result without a model call. The assertions worth writing are the ones that would have caught a real incident: every expected variable appears, no unresolved placeholders remain, the rendered length stays inside the provider's window, and the output-format instructions the downstream parser depends on are still present.

python
from dataclasses import dataclass


@dataclass
class RenderCheck:
    name: str
    predicate: callable
    description: str


class PromptSuite:
    def __init__(self, store, prompt_name: str):
        self.store = store
        self.prompt_name = prompt_name
        self.checks: list[RenderCheck] = []

    def expect_contains(self, needle: str, name: str | None = None):
        self.checks.append(RenderCheck(
            name=name or f"contains {needle!r}",
            predicate=lambda rendered: needle in rendered,
            description=f"rendered prompt must contain {needle!r}",
        ))
        return self

    def expect_no_placeholders(self):
        def predicate(rendered: str) -> bool:
            return "{" not in rendered and "}" not in rendered
        self.checks.append(RenderCheck(
            "no unresolved placeholders", predicate,
            "all template variables must be substituted",
        ))
        return self

    def expect_token_budget(self, limit: int, approx_chars_per_token: int = 4):
        def predicate(rendered: str) -> bool:
            return len(rendered) // approx_chars_per_token <= limit
        self.checks.append(RenderCheck(
            f"within {limit} tokens", predicate,
            "rendered prompt must fit the configured token budget",
        ))
        return self

    def run(self, **variables) -> list[tuple[str, bool]]:
        rendered = self.store.render(self.prompt_name, **variables)
        return [(c.name, c.predicate(rendered)) for c in self.checks]


def test_support_summary_prompt():
    suite = PromptSuite(store, "support_summary")
    suite.expect_contains("Return JSON") \
         .expect_contains("summary") \
         .expect_no_placeholders() \
         .expect_token_budget(1200)
    results = suite.run(ticket_text="Order 1234 shipped late", tone="neutral")
    assert all(passed for _, passed in results)

Keep the character-per-token approximation honest: it is a gate against gross overshoot, not a substitute for a real tokenizer in the one test that needs precision.

Isolating the model with mocks and fixtures

Mock the model client, not the world. Record a library of realistic responses — happy path, empty result, refusal, malformed JSON, truncated output — and replay them in tests for the orchestration layer. This is where parsing bugs surface: the provider wraps JSON in code fences, includes a preamble sentence, or returns a list where an object was expected. Each of those has happened in production somewhere; each is free to test with a fixture.

Fixtures should be versioned beside the code and annotated with the provider response shape they represent, so a deliberate upgrade of the response format is a deliberate edit to the fixture library rather than a surprise failure.

Output quality checks that do not flake

Model-in-the-loop checks must tolerate legitimate variation. Assert on properties: the response parses as JSON with the required keys, its length falls inside a band, it contains a required entity when the input names one, and it avoids a list of forbidden strings known to indicate hallucinated policies. For graded qualities, score rather than assert: run the faithfulness or relevance scorer and compare the score against a stored baseline with a tolerance, failing only on regressions beyond it.

Sampling temperature matters here. Run graded checks at temperature zero where the provider supports it, and where it does not, evaluate three samples and use the median score. A single sample at high temperature measures the model's luck, not your application's quality.

Regression baselines and comparison

Regression testing answers a different question than quality testing: not "is this good?" but "is this worse than last month's version?" Store a baseline per test case — the prompt, the response, and the scores — and on each run compare current output against it with a similarity measure plus the graded scores. Flag when similarity drops sharply (behaviour changed) or when scores regress (behaviour worsened), and require an explicit baseline update to accept the new state, so nothing changes silently.

Refresh baselines deliberately, after a human reviews the diff. Baselines updated automatically by the failing test itself will happily ratify a regression the first time it appears.

python
import json
from pathlib import Path


class RegressionHarness:
    def __init__(self, baseline_dir: str = "baselines", similarity_floor: float = 0.8):
        self.dir = Path(baseline_dir)
        self.dir.mkdir(parents=True, exist_ok=True)
        self.floor = similarity_floor

    def run(self, case_id: str, prompt: str, response: str) -> dict:
        path = self.dir / f"{case_id}.json"
        if not path.exists():
            path.write_text(json.dumps(
                {"prompt": prompt, "response": response}, indent=2))
            return {"case": case_id, "status": "baseline_created"}

        baseline = json.loads(path.read_text())
        similarity = self._jaccard(baseline["response"], response)
        return {
            "case": case_id,
            "status": "passed" if similarity >= self.floor else "regression",
            "similarity": similarity,
            "baseline_chars": len(baseline["response"]),
            "current_chars": len(response),
        }

    @staticmethod
    def _jaccard(a: str, b: str) -> float:
        set_a, set_b = set(a.lower().split()), set(b.lower().split())
        union = set_a | set_b
        return len(set_a & set_b) / len(union) if union else 1.0

Word-level Jaccard is a coarse but stable change detector; pair it with the graded scores so a stylistic rewrite (low similarity, flat scores) is distinguished from a behavioural regression (moderate similarity, falling scores).

Running the suite in CI without breaking the bank

The full pyramid does not belong on every commit. Run prompt unit tests and mocked integration tests on every push — they are free and should gate the build. Run the model-in-the-loop suite on pull requests that touch prompts, models, or retrieval configuration, against a reduced evaluation set, and promote to the full set nightly. Cache judge results by content hash so re-running an unchanged prompt costs nothing.

Set the gate as a comparison to the stored baseline rather than an absolute score, and make the failure message name the metric, the delta, and the report link. A gate that says "faithfulness dropped from 0.88 to 0.79 on 12 cases" gets fixed; a gate that says "test failed" gets bypassed.

Common Mistakes

Asserting exact string equality on model outputs

Fix: Assert deterministic properties — parsing, budgets, required fields — and score graded qualities against a baseline.

Testing prompts in isolation while trusting the orchestration layer

Fix: Add mocked integration tests that replay recorded responses, including malformed and truncated shapes.

Updating regression baselines automatically when a test fails

Fix: Require a reviewed baseline diff so intentional behaviour changes are accepted consciously.

Running metered model-in-the-loop tests on every commit

Fix: Gate commits on free tests; run scored evaluations on relevant pull requests and nightly on a reduced set.

Key Takeaways

  • Test properties, not strings: parsing, budgets, schemas and similarity envelopes tolerate legitimate variation.
  • Push deterministic logic out of the model and test it like ordinary code with zero inference cost.
  • Mocked integration tests catch response-envelope and tool-routing bugs that prompt tests cannot see.
  • Score graded qualities against stored baselines with a tolerance, using temperature zero or median-of-three sampling.
  • Regression baselines are updated only through reviewed diffs, never by the failing run itself.
  • Tier the suite by cost: free checks gate every commit, metered evaluations gate prompt changes and nightly runs.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement