Building LLM Test Suites: Unit Tests for Prompts and Chain Behavior

Building LLM Test Suites: Unit Tests for Prompts and Chain Behavior

Testing LLM-powered applications is fundamentally different from testing deterministic software, but that does not mean you throw away the discipline of unit testing. It means you adapt it. Prompts are code. Chains are logic. Both can be tested, mocked, and validated in automated suites that catch regressions before they reach users.

This post covers the full stack of LLM unit testing: how to structure tests for individual prompts, how to test LangChain and LlamaIndex chains, how to mock LLM calls for fast test runs, and how to write meaningful assertions for outputs that are inherently non-deterministic.


What Makes LLM Testing Different

In standard unit testing, you call a function with known inputs and assert exact outputs. With LLMs:

  • Outputs are non-deterministic — even at temperature=0, minor changes to model versions can shift outputs
  • The "function" is a remote API call — tests are slow and expensive if you hit real endpoints
  • Quality is multidimensional — correct, wrong, and slightly-wrong are not binary states
  • Context matters — a prompt that works for one input type may fail subtly on another

The solution is not to abandon unit testing but to design tests that assert on properties of the output rather than exact strings, and to use mocks aggressively for fast iteration.


Testing Individual Prompts

Start with the smallest unit: a single prompt template and its expected behavior.

Structure Your Prompts for Testability

Prompts that are buried as inline strings in application code are hard to test. Extract them into versioned modules.

# prompts/classification.py
from dataclasses import dataclass
from string import Template

@dataclass
class ClassificationPrompt:
    system: str = """You are a customer support classifier.
Classify the customer message into one of these categories:
- billing
- technical_issue
- feature_request
- general_inquiry

Respond with only the category name, lowercase."""

    user_template: str = "Customer message: $message"

    def format(self, message: str) -> list[dict]:
        return [
            {"role": "system", "content": self.system},
            {"role": "user", "content": Template(self.user_template).substitute(message=message)}
        ]

Now you can test the prompt structure independently of any LLM call.

# tests/test_classification_prompt.py
import pytest
from prompts.classification import ClassificationPrompt

def test_prompt_formats_message_correctly():
    prompt = ClassificationPrompt()
    messages = prompt.format("I was charged twice this month")
    assert len(messages) == 2
    assert messages[0]["role"] == "system"
    assert messages[1]["role"] == "user"
    assert "I was charged twice this month" in messages[1]["content"]

def test_system_prompt_contains_all_categories():
    prompt = ClassificationPrompt()
    for category in ["billing", "technical_issue", "feature_request", "general_inquiry"]:
        assert category in prompt.system

These tests run in milliseconds, need no API calls, and catch the most common prompt bugs: missing variables, broken templates, and missing instructions.


Mocking LLM Calls

The most important optimization in an LLM test suite is eliminating real API calls from fast test paths.

Mocking with unittest.mock

# tests/test_classifier.py
from unittest.mock import patch, MagicMock
import pytest
from app.classifier import classify_message

def make_mock_completion(content: str):
    mock = MagicMock()
    mock.choices[0].message.content = content
    return mock

@patch("app.classifier.openai_client.chat.completions.create")
def test_classify_billing_message(mock_create):
    mock_create.return_value = make_mock_completion("billing")

    result = classify_message("I was charged twice this month")

    assert result == "billing"
    mock_create.assert_called_once()

@patch("app.classifier.openai_client.chat.completions.create")
def test_classify_handles_unexpected_response(mock_create):
    mock_create.return_value = make_mock_completion("unknown_category")

    result = classify_message("I was charged twice this month")

    assert result == "general_inquiry"  # Should fall back to default

Fixtures for Common Response Patterns

# tests/fixtures/llm_responses.py
import pytest
from unittest.mock import MagicMock

@pytest.fixture
def mock_llm_factory():
    def _factory(response_content: str, model: str = "gpt-4o"):
        mock = MagicMock()
        mock.choices = [MagicMock()]
        mock.choices[0].message.content = response_content
        mock.choices[0].finish_reason = "stop"
        mock.model = model
        mock.usage.total_tokens = 150
        return mock
    return _factory

@pytest.fixture
def mock_llm_billing(mock_llm_factory):
    return mock_llm_factory("billing")

@pytest.fixture
def mock_llm_json_response(mock_llm_factory):
    import json
    return mock_llm_factory(json.dumps({
        "category": "billing",
        "confidence": 0.95,
        "reasoning": "Message mentions being charged"
    }))

Using pytest-recording or VCR for API Fixtures

For integration tests that do need real responses, record once and replay.

# Install: pip install pytest-recording vcrpy
# Usage: run once with --record-mode=new_episodes, then tests use cassettes

import pytest

@pytest.mark.vcr
def test_real_classification_integration():
    from app.classifier import classify_message
    result = classify_message("My payment failed yesterday")
    assert result in ["billing", "technical_issue"]

Cassette files are committed to the repo. Tests replay the recorded HTTP interaction instead of hitting the API.


Testing LangChain Chains

LangChain introduces additional complexity: chains compose multiple LLM calls, tools, and memory. Testing them requires a layered approach.

Unit Testing Individual Chain Components

# app/chains/support_chain.py
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI

def build_support_chain(llm=None):
    if llm is None:
        llm = ChatOpenAI(model="gpt-4o", temperature=0)

    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a helpful support agent. Be concise."),
        ("human", "{question}")
    ])

    return prompt | llm | StrOutputParser()

By accepting an llm parameter, you can inject a mock for testing:

# tests/test_support_chain.py
from unittest.mock import MagicMock
from langchain_core.messages import AIMessage
from app.chains.support_chain import build_support_chain

def test_chain_passes_question_to_llm():
    mock_llm = MagicMock()
    mock_llm.invoke.return_value = AIMessage(content="Here is the answer.")

    chain = build_support_chain(llm=mock_llm)
    result = chain.invoke({"question": "How do I reset my password?"})

    assert result == "Here is the answer."
    mock_llm.invoke.assert_called_once()

    # Verify the prompt contained the question
    call_args = mock_llm.invoke.call_args[0][0]
    assert any("How do I reset my password?" in str(msg) for msg in call_args)

Testing RAG Chains

RAG chains add a retrieval step. Test the retrieval and generation separately.

# tests/test_rag_chain.py
from unittest.mock import MagicMock, patch
from langchain_core.documents import Document
from app.chains.rag_chain import build_rag_chain

@pytest.fixture
def mock_retriever():
    retriever = MagicMock()
    retriever.invoke.return_value = [
        Document(
            page_content="Password reset is available under Account Settings > Security.",
            metadata={"source": "help-docs/account.md"}
        )
    ]
    return retriever

def test_rag_chain_uses_retrieved_context(mock_retriever):
    mock_llm = MagicMock()
    mock_llm.invoke.return_value = AIMessage(
        content="Go to Account Settings > Security to reset your password."
    )

    chain = build_rag_chain(retriever=mock_retriever, llm=mock_llm)
    result = chain.invoke({"question": "How do I reset my password?"})

    # Verify retriever was called
    mock_retriever.invoke.assert_called_once_with("How do I reset my password?")

    # Verify the context was passed to the LLM
    llm_call_content = str(mock_llm.invoke.call_args)
    assert "Account Settings" in llm_call_content

    assert "Account Settings" in result

Snapshot Testing for Prompt Outputs

Snapshot testing captures the exact output of a prompt on a known input and fails the test if that output changes. It is useful for detecting unintended prompt regressions.

# Install: pip install syrupy
# tests/test_prompt_snapshots.py
import pytest
from syrupy.assertion import SnapshotAssertion

@pytest.fixture
def llm_snapshot(snapshot):
    return snapshot.with_defaults(extension_class=JSONSnapshotExtension)

@patch("app.classifier.openai_client.chat.completions.create")
def test_classification_output_snapshot(mock_create, snapshot):
    mock_create.return_value = make_mock_completion("billing")

    result = classify_message("I was charged twice this month")

    assert result == snapshot  # First run: creates snapshot. Subsequent: compares.

The snapshot is stored in tests/__snapshots__/ and committed to version control. When prompt changes intentionally alter output, you run pytest --snapshot-update to accept the new snapshot.

This is particularly useful for structured output prompts where you want to verify the JSON schema of responses does not change unexpectedly.


Assertion Strategies for Non-Deterministic Outputs

For tests that do hit real LLM endpoints (integration tests), exact-match assertions will be fragile. Use property-based assertions instead.

Structural Assertions

import json
import pytest

def test_product_description_structure():
    """Test that the output has required fields, regardless of content."""
    result = generate_product_description("Wireless noise-canceling headphones")
    data = json.loads(result)

    assert "headline" in data
    assert "body" in data
    assert "cta" in data
    assert len(data["headline"]) <= 60, "Headline must fit in 60 chars"
    assert len(data["body"]) >= 50, "Body must have meaningful content"

Semantic Assertions with Embeddings

from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity

model = SentenceTransformer("all-MiniLM-L6-v2")

def assert_semantically_similar(actual: str, expected: str, threshold: float = 0.7):
    embeddings = model.encode([actual, expected])
    sim = float(cosine_similarity([embeddings[0]], [embeddings[1]])[0][0])
    assert sim >= threshold, (
        f"Semantic similarity {sim:.3f} below threshold {threshold}.\n"
        f"Expected: {expected}\nActual: {actual}"
    )

def test_summary_is_semantically_correct():
    source = "The product launch exceeded expectations with 50,000 units sold in the first week."
    summary = summarize(source)
    assert_semantically_similar(
        summary,
        "Strong product launch with high first-week sales volume.",
        threshold=0.65
    )

LLM-Graded Assertions

For complex outputs, use a separate LLM call as the assertion.

def llm_assert(output: str, requirement: str, model: str = "gpt-4o-mini") -> None:
    """Assert that output meets a natural-language requirement."""
    client = openai.OpenAI()
    response = client.chat.completions.create(
        model=model,
        messages=[{
            "role": "user",
            "content": f"""Does the following text meet this requirement?

Requirement: {requirement}

Text: {output}

Answer with only 'yes' or 'no'."""
        }],
        temperature=0
    )
    answer = response.choices[0].message.content.strip().lower()
    assert answer == "yes", f"LLM assertion failed: '{requirement}'\nOutput: {output}"

def test_email_response_is_professional():
    email = generate_support_email(ticket="Can't log in")
    llm_assert(email, "The response is professional and does not contain any rude language")
    llm_assert(email, "The response acknowledges the customer's issue")
    llm_assert(email, "The response offers a next step or solution")

Organizing Your LLM Test Suite

A practical directory structure:

tests/
  unit/
    test_prompts.py          # Prompt structure, template formatting
    test_output_parsers.py   # Output parsing, schema validation
    test_chain_components.py # Individual chain nodes with mocks
  integration/
    test_chains.py           # Full chain runs with VCR cassettes
    test_rag_retrieval.py    # Retrieval quality tests
  eval/
    test_output_quality.py   # Semantic quality, LLM-as-judge
    golden_dataset.jsonl     # Reference inputs/outputs
  cassettes/                 # VCR recorded responses
    test_chains/
      test_billing_classification.yaml

Run unit tests on every commit (fast, no API calls). Run integration tests on PR merge. Run eval tests nightly or before releases.


CI Integration and Cost Management

LLM tests can get expensive quickly. Practical guardrails:

# .github/workflows/test.yml
jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - run: pytest tests/unit/ -v --tb=short

  integration-tests:
    runs-on: ubuntu-latest
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
    steps:
      - run: pytest tests/integration/ -v --timeout=30

  eval-tests:
    runs-on: ubuntu-latest
    if: github.event_name == 'schedule'
    steps:
      - run: pytest tests/eval/ -v --eval-model=gpt-4o-mini

Use cheaper models (gpt-4o-mini, claude-haiku) for automated eval assertions. Reserve gpt-4o for cases where evaluation quality actually matters for the specific test.


Connecting to End-to-End Testing

Unit tests for LLM prompts and chains cover the logic layer. But users interact with your AI application through a UI or API. Platforms like HelpMeTest complement your unit test suite by running end-to-end tests against the full application — verifying that the outputs of your chains reach users correctly, that error states are handled gracefully, and that the overall user experience works as intended. The two levels are complementary: unit tests give you fast feedback on prompt logic; end-to-end tests confirm the whole system holds together.


Summary

LLM unit testing is achievable with disciplined engineering:

  1. Extract prompts into versioned, testable modules
  2. Mock aggressively — real API calls belong in integration tests, not unit tests
  3. Use VCR/cassettes for integration tests that need real recorded responses
  4. Assert on properties, not exact strings — structure, semantics, and LLM-graded criteria
  5. Layer your test suite — unit (fast/always), integration (on merge), eval (nightly)

The goal is not to eliminate the probabilistic nature of LLMs — it is to build a safety net that catches the 90% of regressions that are straightforward, so you can focus human attention on the edge cases that are genuinely hard.

Read more

Start now free