AI Application Testing Strategy
AI wrote a feature and then wrote the property and unit tests too. Everything passes green, yet production still breaks—because AI-generated implementation and AI-generated tests share the same hidden assumptions. Testing AI-era applications requires separating two boundaries: deterministic AI-generated code (verified with boundaries, properties, contracts, and red-teaming) and non-deterministic LLM call boundaries (verified with network mocks for caller contracts plus offline/online evaluations for model quality).
Core Challenge: Testability of AI Code and Model Boundaries
Testing AI-assisted systems introduces three recurring failure modes:
Challenge 1: Model Non-Determinism
LLM responses are stochastic: identical inputs can produce different phrasing across runs. Rigid “assert exact string equality” breaks down at the model boundary—split caller contract tests (mocked) from model quality evaluation (scored datasets).
Challenge 2: Requirement Mismatch
AI often produces logically self-consistent code that disagrees with business rules—for example, a mathematically valid discount function that returns negative prices when discount exceeds 100% instead of clamping to zero.
Challenge 3: Shared Blind Spots
When AI writes both code and tests in one pass, both encode the same misunderstanding. If the model assumes an empty array is invalid, the implementation throws and the test asserts that it throws—green CI, broken requirement.
Boundary Testing + Property Testing
Go beyond happy paths and test invariants—properties that must hold across all valid inputs. In TypeScript, pair Vitest with fast-check to generate edge cases automatically:
import { describe, expect, it } from "vitest";
import fc from "fast-check";
export function calculateDiscountedPrice(price: number, discountPct: number): number {
if (!Number.isFinite(price) || price < 0) {
throw new RangeError("Price must be a non-negative finite number");
}
const discount = Math.min(Math.max(discountPct, 0), 100); // clamp to 0–100
return price * (1 - discount / 100);
}
describe("calculateDiscountedPrice", () => {
it("satisfies core pricing invariants across generated inputs", () => {
fc.assert(
fc.property(
fc.double({ min: 0, max: 10_000, noNaN: true }),
fc.double({ min: 0, max: 100, noNaN: true }),
(price, discount) => {
const result = calculateDiscountedPrice(price, discount);
expect(result).toBeLessThanOrEqual(price + 1e-9); // never exceeds original price
expect(result).toBeGreaterThanOrEqual(0); // never negative
if (discount === 0) {
expect(Math.abs(result - price)).toBeLessThan(1e-9);
}
},
),
{ numRuns: 500 },
);
});
it.each([
[0, 10, 0], // zero price
[100, 0, 100], // zero discount
[100, 100, 0], // full discount
[100, 150, 0], // discount over 100% clamped
])("handles edge case price=%d discount=%d -> %d", (price, discount, expected) => {
expect(calculateDiscountedPrice(price, discount)).toBe(expected);
});
});fast-check explores zero, tiny floats, and extremes automatically—and shrinks any failure down to the minimal counterexample.
Mock LLM Responses
Do not hit live LLM APIs in unit tests or CI—they are slow, costly, and flaky. Intercept HTTP calls at the network layer with MSW (Mock Service Worker) to verify request construction, retries, and error handling:
import { afterAll, afterEach, beforeAll, expect, it } from "vitest";
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
async function summarizeText(text: string): Promise<string> {
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "gpt-4o",
messages: [{ role: "user", content: `Summarize: ${text}` }],
}),
});
if (!res.ok) throw new Error(`Upstream HTTP ${res.status}`);
const data = (await res.json()) as { choices: Array<{ message: { content: string } }> };
return data.choices[0]?.message.content ?? "";
}
const server = setupServer(
http.post("https://api.openai.com/v1/chat/completions", () =>
HttpResponse.json({
choices: [{ message: { content: "This is a summary." } }],
}),
),
);
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it("parses mocked completion payload", async () => {
await expect(summarizeText("Long text here...")).resolves.toBe("This is a summary.");
});Keep the boundary clear: mocks prove caller contract correctness (including 429 rate limits, 500s, and empty responses), but never replace dataset-backed model evaluations.
Snapshot Testing (Golden Files)
For deterministic prompt templates and structured report formatters, guard against accidental regressions with Vitest’s toMatchFileSnapshot:
import { expect, it } from "vitest";
it("renders Q4 report prompt stably", async () => {
const rendered = buildReportPrompt({ sales: 1000, period: "2026-Q4" });
await expect(rendered).toMatchFileSnapshot("./__snapshots__/report_q4.txt");
});When to update snapshots:
- ✅ Product requirements changed and output format should change
- ✅ A bug fix makes the new output more accurate than the old snapshot
- ❌ Unexplained failure — investigate the diff first instead of blindly passing
-u
Commit snapshot files to Git so reviewers inspect output diffs directly in PRs.
Contract Testing
AI refactoring can quietly rename fields or loosen return shapes. Enforce both compile-time TypeScript types and runtime Zod schemas:
import { z } from "zod";
import { expect, it } from "vitest";
const SearchResultSchema = z.object({
id: z.string().min(1),
title: z.string().min(1),
score: z.number().min(0).max(1),
metadata: z.record(z.string(), z.unknown()),
});
const ToolCallSchema = z.object({
toolName: z.enum(["search", "calculate", "lookup"]),
parameters: z.record(z.string(), z.unknown()),
});
it("enforces search result and tool-call contracts", () => {
const results = searchDocuments("test query");
expect(() => z.array(SearchResultSchema).parse(results)).not.toThrow();
const toolCall = getLlmToolCall("search for X");
expect(() => ToolCallSchema.parse(toolCall)).not.toThrow();
});Enforce strict type checking in CI:
pnpm exec tsc --noEmitHuman Review Gate
AI-generated tests must pass human review before becoming trusted gates.
Flag AI-generated test files in CI:
# .github/workflows/ci.yml
- name: Check for AI-generated test files
run: |
ai_tests=$(grep -rl "// AI-generated" tests/ || true)
if [ -n "$ai_tests" ]; then
echo "::warning::AI-generated test files detected, require human review:"
echo "$ai_tests"
fiRed-team the tests:
- Read every assertion and spot gaps between what the tests check and what the requirement demands
- Imagine a “cheater implementation” that satisfies the tests while ignoring the real goal
- If the cheater passes, tighten the assertions
For example, if a test only asserts “returns a non-empty string”, return "a" passes green—proving the test does not check output quality or invariants.