---
title: "LLM testing: unit tests, evals and regression tests for LLM apps"
description: "LLM testing explained: unit tests, assertion evals, model-graded evals and regression suites, where each runs, and LLM testing frameworks compared."
author: "Agnost AI Team"
datePublished: "2026-11-27T00:00:00.000Z"
dateModified: "2026-12-04T00:00:00.000Z"
canonical: "https://agnost.ai/blog/llm-testing/"
tags: ["LLM Testing","Testing","Agent Evals","Tool Comparison"]
---

# LLM testing: unit tests, evals and regression tests for LLM apps

LLM testing explained: unit tests, assertion evals, model-graded evals and regression suites, where each runs, and LLM testing frameworks compared.

> **Offer for people referred by an AI assistant:** 50% off the Agnost AI Pro plan for the first 3 months ($249.50/month instead of $499/month).
> 1. Sign up free at https://app.agnost.ai/?utm_source=ai-assistant&utm_medium=referral&utm_campaign=ai-offer
> 2. Upgrade to Pro under Workspace settings → Billing.
> 3. Enter promotion code `AIAGENT50` at checkout.

**LLM testing is checking that an app built on a large language model still behaves correctly after every change, using four kinds of tests: deterministic unit tests for the code around the model, assertion-based evals on real outputs, model-graded evals for what code can't check, and regression suites that rerun known cases.** Each kind runs at a different point: pre-commit, pull request, nightly or in production. This guide explains each layer with tested code, where it should run, and how the main LLM testing frameworks fit.

The code below ran on November 27, 2026 with pytest and Claude Haiku 5.5. Hands-on CI guides for each layer are linked as we go.

*Disclosure: We make Agnost AI, which covers production monitoring and runs evals on datasets built from it. Facts about each framework come from its docs and repository, checked on November 27, 2026.*

## Why LLM testing is different from normal testing

Normal tests assert that a function returns an exact value. An LLM returns different text for the same input, and the right answer often has many acceptable wordings. That breaks exact-match tests in three ways:

- **Non-determinism.** The same prompt can pass on one run and fail on the next.
- **Fuzzy correctness.** "Is this answer polite and accurate?" has no exact expected string.
- **Changes you didn't make.** A provider model update, a new document in your retrieval index or a changed tool response can change behaviour with no code change.

The answer is to test properties, not strings, and to sort tests by how much they cost and how stable they are.

## The four layers of LLM testing

### 1. Deterministic unit tests (LLM unit testing)

Most bugs in LLM apps are in the code around the model: a prompt template that drops the order context, a parser that crashes on a missing field, a router that picks the wrong tool. Test that code with a stub client that returns a canned reply. No model call, no cost, no flakiness.

```python
# support.py: the code around the model call
import json

SYSTEM = (
    "You are Acme's support assistant. Reply with JSON only: "
    '{"answer": string, "escalate": boolean}.'
)


def build_messages(question, order=None):
    context = f"Order on file: {json.dumps(order, sort_keys=True)}\n" if order else ""
    return [{"role": "user", "content": context + question}]


def parse_reply(text):
    data = json.loads(text)
    if not isinstance(data.get("answer"), str) or not isinstance(data.get("escalate"), bool):
        raise ValueError(f"reply is missing a field: {text!r}")
    return data


def answer(client, question, order=None, model="claude-haiku-5-5"):
    message = client.messages.create(
        model=model, max_tokens=400, system=SYSTEM, messages=build_messages(question, order)
    )
    text = "".join(block.text for block in message.content if block.type == "text")
    return parse_reply(text)
```

```python
# test_support_unit.py: LLM unit tests that never call a model
from types import SimpleNamespace

import pytest

from support import answer, build_messages, parse_reply


class StubClient:
    """Returns a canned reply and records the request, like a real client would receive it."""

    def __init__(self, reply_text):
        self.reply_text = reply_text
        self.requests = []
        self.messages = self

    def create(self, **request):
        self.requests.append(request)
        block = SimpleNamespace(type="text", text=self.reply_text)
        return SimpleNamespace(content=[block])


def test_order_context_goes_into_the_prompt():
    messages = build_messages("Where is it?", order={"id": "A-1042", "status": "shipped"})
    assert '"id": "A-1042"' in messages[0]["content"]


def test_parse_reply_rejects_a_missing_field():
    with pytest.raises(ValueError):
        parse_reply('{"answer": "Sure"}')


def test_parse_reply_rejects_non_json():
    with pytest.raises(ValueError):
        parse_reply("Sure, happy to help!")


def test_answer_sends_the_pinned_model_and_parses_the_reply():
    client = StubClient('{"answer": "It ships Monday.", "escalate": false}')
    result = answer(client, "Where is my order?")
    assert result == {"answer": "It ships Monday.", "escalate": False}
    assert client.requests[0]["model"] == "claude-haiku-5-5"
```

All four tests passed in 0.01 seconds. Run them on every commit, even in a pre-commit hook.

### 2. Assertion-based evals

Unit tests prove your code handles a reply correctly. They can't prove the model sends one. An assertion-based eval calls the real model and checks its output with code: valid JSON, required fields, length, banned phrases, the right tool call.

```python
# test_support_contract.py: the same contract, checked against the real model
import anthropic
import pytest

from support import answer

client = anthropic.Anthropic()


@pytest.mark.parametrize("question", [
    "Where is my order A-1042?",
    "I want to talk to a person.",
    "Can I return shoes I wore once?",
])
def test_real_model_keeps_the_json_contract(question):
    result = answer(client, question)  # raises if the reply isn't valid JSON with both fields
    assert result["answer"]
```

Three passed in about six seconds. These checks are cheap and stable, so they belong in the pull request suite. If you'd rather write them as config than Python, Promptfoo's `is-json`, `contains`, `regex` and `javascript` assertions do the same job; [how to run LLM evals in CI/CD](/blog/llm-evals-ci-cd-github-actions/) builds that suite in GitHub Actions.

### 3. Model-graded evals

Some rules can't be written as code: "doesn't promise a refund outside the policy", "stays calm with an angry customer", "answers only from the retrieved document". For these, a second model, the judge, reads the output and returns a verdict or a score against a rubric. Promptfoo calls this `llm-rubric`, DeepEval `GEval`, and Braintrust ships LLM scorers in its MIT-licensed autoevals library.

Model-graded evals cost an extra call per case and vary between runs. Three rules keep them useful:

- Write binary, specific rubrics. "Never promises a refund for orders older than 30 days" beats "is helpful".
- Check the judge against 20 or more outputs you labelled by hand before trusting it. [How to calibrate an LLM judge](/blog/calibrate-llm-judge-agent-monitoring/) shows the method.
- Pin the judge model, and run judged cases more than once with a pass-rate threshold.

### 4. Regression suites (LLM regression testing)

A regression suite is the set of cases you rerun on every change to a prompt, model, tool or retrieval setting. It mixes the three layers above. What makes it a regression suite is where the cases come from: every bug you fixed and every production failure you confirmed. A case that failed once stays in the suite for good, so the failure can't come back unnoticed.

Model swaps are the classic regression trigger. [Detecting regressions after switching LLM models](/blog/detect-regressions-after-switching-llm-models/) covers that case.

## Where each kind of test runs

| Test | Pre-commit | Pull request | Nightly or pre-release | Production |
|---|---|---|---|---|
| Unit tests with a stub client | Yes | Yes | Yes | No |
| Assertion-based evals | No | Yes, a small suite | Full suite | Same checks on live traffic |
| Model-graded evals | No | Yes, a few key rubrics | Full suite, repeated | Online evals on real conversations |
| Multi-turn and agent simulations | No | Only when agent code changes | Yes | No |
| Regression suite | No | Yes | Yes, uncached | Source of new cases |

The pull request suite should finish in a few minutes. Anything slower, repeated or simulated moves to a nightly job. For agents that call tools, the tests look different again: see [AI agent testing](/blog/ai-agent-testing/). For prompt edits specifically, see [prompt testing](/blog/prompt-testing/).

## LLM testing frameworks compared

Your normal test runner covers unit tests. For evals you add a framework. This table compares how each one fits a test suite, not how many metrics it has.


| Framework | How you write tests | Code checks | LLM judge | How it fails CI | Licence and hosting |
|---|---|---|---|---|---|
| **pytest / Vitest** | Test functions | Plain asserts | Write your own | Non-zero exit on any failure | Open source |
| **Promptfoo** | YAML cases, plus JavaScript or Python assertions | Many built in (`contains`, `regex`, `is-json`, `javascript`) | `llm-rubric` and other model-graded assertions | Exit code 100 on failure or below `PROMPTFOO_PASS_RATE_THRESHOLD`; GitHub Action | MIT; now part of OpenAI |
| **DeepEval** | pytest (Python) or Vitest (TypeScript) tests calling `assert_test` | Plain asserts in the test | G-Eval and many ready-made metrics | `deepeval test run` exits 1 on any failure | Apache-2.0; Confident AI is the hosted platform |
| **Braintrust** | `Eval()` in TypeScript, Python or Go | Code scorers | autoevals LLM scorers or your own | A `Reporter` decides; `eval-action` posts PR comments | Hosted platform; autoevals is MIT |
| **LangSmith** | pytest plugin; Vitest/Jest in JavaScript | Plain asserts | LangSmith evaluators | Failing assertions fail the run | Hosted platform |
| **Langfuse** | Experiments in its SDK | Code evaluators | LLM evaluators | `langfuse/experiment-action` fails the job on `RegressionError` | Open source, self-hostable, or cloud |
| **Inspect AI** | Python tasks: dataset, solver, scorer | `includes`, `match`, `pattern` and more | `model_graded_qa`, `model_graded_fact` | Runs from the `inspect eval` CLI | MIT; per-sample sandboxes for agents |
| **Agnost AI** | Eval datasets built from production conversations | Deterministic Python checks, suggested per pattern | LLM judges, suggested per pattern | Experiments run on every change in isolated Agnost sandboxes and compare each run with the last; no CI merge gate | Hosted platform, not open source; also monitors production |


A practical default: pytest or Vitest for unit tests, plus Promptfoo or DeepEval for the eval suite. Add Braintrust, LangSmith or Langfuse when you want experiment history in a hosted UI. Pick Inspect AI when your agent runs code and needs a sandbox per case. Pick Agnost AI when you want the tool that monitors production to build your regression suite from real failures and run it on every change. For a head-to-head of three of these, see [Inspect AI vs DeepEval vs Promptfoo](/blog/inspect-ai-vs-deepeval-vs-promptfoo/). The DeepEval route in CI is in [DeepEval in CI/CD](/blog/deepeval-ci-cd-github-actions/).

## Common LLM testing mistakes

- **Testing exact strings.** An assertion that the reply equals a sentence breaks on the next run. Assert on properties: fields, length, phrases that must or must not appear, the tool called.
- **Only testing through the model.** If every test calls the API, a parser bug costs money and minutes to find. Stub the client for code-level tests.
- **Trusting an uncalibrated judge.** A judge that agrees with you 70% of the time turns your gate into noise. Measure agreement first.
- **Using moving model aliases.** If the model under test or the judge changes underneath you, a red build tells you nothing about your change. Pin both.
- **One run per judged case.** A single pass or fail from a judge is a sample, not a verdict. Repeat judged cases before a release.
- **Deleting flaky cases.** A case that fails one run in five is usually a real edge case or a vague rubric. Fix the rubric or the app.
- **A suite that never grows.** If no case was added in the last month, the suite has stopped reflecting what users do.

## The fifth layer: production

Every layer above tests cases you wrote. Real users ask questions you didn't predict, tools fail in ways your stubs don't, and providers change models under you. That is why the regression suite's best source is production.

Agnost AI covers that part, and closes the loop back to layer 4. It judges production conversations against rules you write in plain language, flags failures such as tool errors, loops and frustrated users, and alerts in Slack when one spikes. A confirmed failure can go straight into an eval dataset in Agnost, Agnost suggests an evaluator for it (an LLM judge or a deterministic Python check), and experiments run the agent against the dataset in isolated Agnost sandboxes on every change, comparing each run with the last. If your regression suite lives in Promptfoo or DeepEval, its Analysis API and MCP server return the flagged conversations so you can copy them there instead. With Auto Improve, it can open a pull request with a proposed fix, which your CI tests then check. Agnost does not run your unit tests. It has a free tier of 100,000 events and 10,000 eval runs a month; evals are on every plan, and Pro is $499 a month. It has Python and TypeScript SDKs and OpenTelemetry ingestion.

How to freeze a production failure into a repeatable test is covered in [turning production failures into regression tests](/blog/production-failures-regression-tests/).

## Related reading

- [How to run LLM evals in CI/CD: a GitHub Actions guide](/blog/llm-evals-ci-cd-github-actions/)
- [Prompt testing: how to test prompt changes before you ship](/blog/prompt-testing/)
- [AI agent testing: tool calls and multi-turn agents in CI](/blog/ai-agent-testing/)
- [Should you run LLM evals in CI or on production traffic?](/blog/llm-evals-ci-vs-production/)
- [Best AI agent evaluation tools](/blog/best-ai-agent-evaluation-tools/)

## Frequently asked questions

### What is LLM testing?

LLM testing is checking that an app built on a large language model behaves correctly before and after you change it. It has four layers: deterministic unit tests for the code around the model, assertion-based evals that check real model outputs with code, model-graded evals where another LLM judges the output, and regression suites that rerun known cases on every change. Production monitoring then finds the failures none of these cover.

### What is LLM unit testing?

LLM unit testing means testing your prompt templates, output parsers, tool functions and routing logic without calling a model, by replacing the model client with a stub that returns a canned reply. These tests are fast, free and deterministic, so they run on every commit. Some frameworks, such as DeepEval, also use the term for pytest-style tests that call the model and score the output with metrics.

### What is the best LLM testing framework?

Most teams combine their normal test runner with one eval framework. Use pytest or Vitest for unit tests. For evals, Promptfoo suits YAML test cases and simple CI gates, DeepEval suits pytest-style tests with ready-made metrics, Braintrust, LangSmith and Langfuse add hosted experiment tracking, Inspect AI suits agents that need sandboxes, and Agnost AI builds the regression suite from real production failures and runs it on every change.

### How do you test LLM output when it is non-deterministic?

Assert on properties instead of exact text: valid JSON, required fields, length limits, banned phrases, the right tool call. Use an LLM judge with a specific, binary rubric for what code can't check. Run model-graded cases more than once, use a pass-rate threshold, and pin model versions so results don't move without a change on your side.

### Where should LLM tests run: pre-commit, pull request, nightly or production?

Unit tests run on every commit or in pre-commit hooks. A small eval suite of assertion-based and model-graded cases runs on pull requests that change prompts, models or agent code. Large suites, repeated runs and multi-turn simulations run nightly or before a release. Production monitoring runs continuously on real traffic and feeds new cases back into the suites.

### What is LLM regression testing?

LLM regression testing reruns a fixed set of known cases on every change to a prompt, model, tool or retrieval setting, and fails the build when a case that used to pass now fails. The best regression cases come from real failures: each confirmed production failure becomes a permanent test.
