引言 传统软件测试的基石是确定性:相同输入产生相同输出。LLM Agent 打破了这个前提,让 CI/CD 测试面临根本性挑战。2026年,随着 Agent 评估框架的成熟,一套可落地的 CI/CD 测试方法论终于成型。本文将带你构建完整的 Agent 测试金字塔。
一、Agent 测试金字塔 ┌─────────┐ │ E2E │ ← 端到端场景测试(5-10个) ┌┴─────────┴┐ │ Integration │ ← 多 Agent 协作测试(20-50个) ┌┴──────────────┴┐ │ Evaluation │ ← LLM 评判测试(50-100个) ┌┴──────────────────┴┐ │ Component │ ← 工具/Prompt 测试(200+) ┌┴──────────────────────┴┐ │ Unit Test │ ← 纯函数测试(500+) └───────────────────────────┘ 二、第一层:单元测试(确定性层) 单元测试只测试不涉及 LLM 的部分:数据处理、工具执行的解析逻辑、Prompt 模板渲染。
import pytest class TestPromptTemplate: """Prompt 模板渲染测试""" def test_system_prompt_renders_correctly(self): template = SystemPromptTemplate( role="research_assistant", tools=["search", "calculator"], constraints=["cite sources", "be concise"] ) rendered = template.render() assert "research_assistant" in rendered assert "search" in rendered assert "calculator" in rendered assert "cite sources" in rendered def test_few_shot_template_with_examples(self): template = FewShotTemplate( system="You are a classifier", examples=[ {"input": "I love it", "output": "positive"}, {"input": "Terrible", "output": "negative"}, ], query="{user_input}" ) rendered = template.render(user_input="Amazing!") assert "positive" in rendered assert "negative" in rendered assert "Amazing!" in rendered class TestToolParsing: """工具调用解析测试""" @pytest.mark.parametrize("raw_output,expected_tool,expected_args", [ ('{"tool": "search", "args": {"q": "weather"}}', "search", {"q": "weather"}), ('```json\n{"tool": "calc", "args": {"expr": "1+1"}}\n```', "calc", {"expr": "1+1"}), ('I\'ll use the search tool: {"tool": "search", "args": {"q": "news"}}', "search", {"q": "news"}), ]) def test_parse_tool_call(self, raw_output, expected_tool, expected_args): result = parse_tool_call(raw_output) assert result.tool == expected_tool assert result.args == expected_args def test_parse_malformed_output(self): with pytest.raises(ToolParseError): parse_tool_call("This is not JSON at all") 三、第二层:组件测试(Mock LLM) 使用 Mock LLM 测试 Agent 的控制流,确保工作流逻辑正确。
...