AI Agent在测试设计中的应用
前言
随着AI和大模型(LLM)的诞生以及技术的成熟和普及,测试工程师不仅可以利用 AI 生成和优化测试用例,还能借助 LLM 提高测试覆盖率、减少测试设计的重复性工作,从而专注于更复杂的测试策略和质量保障。
在软件测试的工作流中,分析需求 设计测试点和测试用例是比较繁琐的工作,如何更好的利用大模型技术比如Agent来帮助和赋能呢。
本文将带你构建一个智能 Agent,自动完成如下流程:
① LLM Agent 分析需求 → 生成测试点
Agent 通过调用大语言模型(如 GPT-4)解析需求语义,自动提取出可测试的功能点、边界条件、异常路径等。这一步相当于“从需求生成测试点清单”。
② 基于测试点和需求 → 生成结构化测试用例
接下来,Agent 会结合原始需求与提取出的测试点,生成完整的测试用例。每条用例包含以下内容:
- Title(标题)
- Precondition(前置条件)
- Steps(操作步骤)
- Expected Result(预期结果)
- Actual Result / Pass/Fail(初始测试状态)
这些用例以 JSON 格式输出,方便进一步集成或存储。
③ 将测试用例导出为 Excel 文件
最后一步,Agent 使用 Python 工具(如 pandas + openpyxl)将结构化测试用例保存为 Excel 文件便于后续导入到测试管理平台中
1. 项目搭建
现在开始进行具体项目搭建,项目整体结构如下:
requirement_to_testcase/
│
├── main.py # 项目入口
├── agents/
│ ├── testcase_generator.py # 用于生成测试用例│
├── prompts/
│ ├── parser_prompt.txt
│ ├── generator_prompt.txt
│ └── reviewer_prompt.txt
├── utils/
│ ├── io_utils.py # 处理输入输出、Excel导出等
│ └── format_utils.py # 格式校验与清洗工具
├── requirements.txt
└── README.md
项目主要使用LangChain、OpenAI、pandas等组件,推荐使用Python 3.10+ 环境。
1 . 创建虚拟环境
python -m venv .venv
source .venv/bin/activate # Mac/Linux
# 或
.venv\\Scripts\\activate # Windows
2 . 安装依赖
requirements.txt内容如下
langchain==0.3.25
openai==1.10.0
pandas==2.2.2 # 用于输出表格
openpyxl==3.1.2 # Excel 文件支持
python-dotenv==1.0.1 # 加载 .env 配置
langchain-experimental==0.3.4
安装依赖
pip install -r requirementst.txt
3 . 设置openai的api key
在这个示例中使用的大模型是gpt-3.5,需要在项目中配置API Key,当前大家也可以切换其他大模
在项目根目录下创建一个 .env
文件(若尚未存在),添加以下内容:
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2. 从需求中提取测试
在日常测试用例设计过程中,第一步通常是对需求进行分析并从中提取出测试点,为了让每次大模型的结果更一致效果更好,首先我们需要设计一个prompt
以下是用于“需求 → 测试点”任务的Prompt,可以保存在prompts/generate_test_points.md
方便阅读和维护
你是一名经验丰富的软件测试分析工程师,擅长从自然语言需求中提取出清晰、可验证的测试点。请将以下输入的中文需求描述,转化为一组**测试点清单**,每一条测试点应满足以下要求:1. 语句简洁,覆盖明确的功能或行为;
2. 能指导后续的测试用例设计;
3. 包含主流程、边界条件、异常输入等常见测试场景;
4. 每一条测试点使用 “- ” 开头,按行列出;
5. 不输出多余说明文字,仅返回测试点清单本身。输入需求:
"""
{requirement}
"""请输出测试点列表(每行一个):
-
大家可以在utils.py
或者main.py
中添加load_prompt_template函数,用于读取prompt
def load_prompt_template(path: str) -> str:with open(path, "r", encoding="utf-8") as f:return f.read()
将以下代码添加到 main.py
中,完成Prompt读取并调用ChatGPT:
from dotenv import load_dotenv
from langchain.chains.llm import LLMChain
from langchain_community.chat_models import ChatOpenAI
from langchain_core.prompts import PromptTemplate
from utils import load_prompt_templateload_dotenv()def main():# 加载外部 Prompt 文件prompt_path = "prompts/generate_test_points.md"prompt_text = load_prompt_template(prompt_path)# 解析 Prompt 文件test_point_prompt_template = PromptTemplate(input_variables=["testing_points"],template=prompt_text,)llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo")parser_chain = LLMChain(llm=llm, prompt=test_point_prompt_template)# 示例调用requirement = "用户可以使用邮箱和密码登录系统,成功后跳转到首页。若邮箱或密码错误,应显示错误信息。"test_points = parser_chain.run(requirement)print(test_points)if __name__ == "__main__":main()
运行main.py,模型返回的测试点如下:
- 使用正确的邮箱和密码登录系统,验证是否成功跳转到首页
- 使用错误的邮箱登录系统,验证是否显示错误信息
- 使用错误的密码登录系统,验证是否显示错误信息
- 使用错误的邮箱和密码登录系统,验证是否显示错误信息
- 使用空邮箱登录系统,验证是否显示错误信息
- 使用空密码登录系统,验证是否显示错误信息
3. 生成测试用例Agent
在成功提取测试点之后,下一步是生成具体的测试用例。这边就要开始完成该Agent核心的步骤了
Step 1:设计 Prompt 生成测试用例
为了确保模型生成的测试用例结构清晰、可落地执行、便于导出,我们需要一个规范化的 Prompt。我们将prompt内容保存为 prompts/generate_test_cases.md
:
### 背景说明(Context)你是一名资深的软件测试工程师,负责根据产品需求和测试点设计高质量的测试用例。你的任务是编写结构化、规范化的测试用例,确保:1. 每条测试用例都准确覆盖指定的测试点;
2. 所有测试用例均符合格式要求,具备明确的前置条件、详细的测试步骤及期望结果;
3. 测试用例应覆盖所有测试点,每个测试用例可覆盖 2~3 个测试点,避免重复冗余。---**输入需求:**
"""
{requirement}
"""**测试点列表:**
"""
{test_points}
"""### 输出要求请根据上述需求和测试点,输出结构化的测试用例,格式为 JSON 数组,示例如下:
- 语言应清晰简洁,避免冗长重复;
- 请保证输出为有效 JSON 格式,确保可以被自动解析与导出
- 请确保每个测试用例都能独立执行,避免相互依赖
- 每个测试用例应包含以下内容:- **Title**:简洁明了的测试用例标题- **Description**:对测试目的或覆盖点的简要描述- **Precondition**:测试执行前的前置条件- **Step**:每条用户操作步骤(无需写预期结果)- **Expected Result**:整个用例的总体预期结果- **Actual Result**:测试执行时的实际观察结果- **Pass/Fail**:是否通过,填写 `Pass` 或 `Fail`---### 输出格式
[{{"title": "邮箱密码正确时登录成功","description": "验证邮箱和密码输入正确后可登录系统","precondition": "已打开登录页面","steps": ["输入正确邮箱地址","输入正确密码","点击登录按钮"],"expected_result": "成功跳转到系统首页","actual_result": "待测试","pass_fail": "待测试"}}
]
Step 2:调用 LLM 生成测试用例
在 main.py
中添加如下函数,用于读取Prompt模板并调用大模型生成用例的内容:
def generate_test_cases_from_points(test_points: str, requirement: str) -> str:prompt_path = "prompts/generate_test_cases.md"prompt_text = load_prompt_template(prompt_path)prompt_template = PromptTemplate(input_variables=["requirement", "test_points"],template=prompt_text,validate_template=False # 跳过变量检查)llm = ChatOpenAI(temperature=0.2, model="gpt-3.5-turbo")testcase_chain = LLMChain(llm=llm, prompt=prompt_template)response = testcase_chain.run({"requirement": requirement,"test_points": test_points})return response # 返回的是 JSON 字符串
函数说明
- 从
prompts/generate_test_cases.md
文件中读取Prompt的模板 - 构建 LangChain的
PromptTemplate
,将test_points和requirement注入到prompt模板中 - 使用
gpt-3.5-turbo
模型创建LLMChain
的对象 - 执行Chain,调用大模型并生成结构化测试用例
Step 3:使用 Agent 自动写入 Excel
然后进入最后的一个步骤,原先没有大模型Agent我们会编写一段程序自己导入到Excel。而现在,借助Agent框架,我们可以让大语言模型自动完成这项工作。
导出用例Agent
首先,在 agents
目录下新建 export_excel_agent.py
,添加如下代码:
from langchain.agents import create_react_agent, AgentExecutor
from langchain import hub
from langchain_community.chat_models import ChatOpenAI
from langchain_experimental.tools import PythonREPLTool
from utils import load_prompt_templatedef export_test_cases_with_agent(test_case_json: str, filename: str = "test_cases.xlsx"):# 加载 Prompt 模板prompt_path = "prompts/export_to_excel.md"export_instructions = load_prompt_template(prompt_path)# 加载 ReAct Agent 的基础 Promptbase_prompt = hub.pull("langchain-ai/react-agent-template")prompt = base_prompt.partial(instructions=export_instructions)tools = [PythonREPLTool()]agent = create_react_agent(prompt=prompt,llm=ChatOpenAI(temperature=0, model="gpt-3.5-turbo"),tools=tools,)python_agent = AgentExecutor(agent=agent, tools=tools, verbose=True)result = python_agent.invoke({"input": "请将测试用例写入Excel 文件"})return result
串联整个流程
接下来,我们将测试点提取、用例生成与导出文件的三个步骤整合起来 ,以下是main.py
的完整代码
from dotenv import load_dotenv
from langchain.chains.llm import LLMChain
from langchain_community.chat_models import ChatOpenAI
from langchain_core.prompts import PromptTemplate
from agents.export_excel_agent import export_test_cases_with_agent
import openaifrom utils import load_prompt_templateload_dotenv()def generate_test_cases_from_points(test_points: str, requirement: str) -> str:prompt_path = "prompts/generate_test_cases.md"prompt_text = load_prompt_template(prompt_path)prompt_template = PromptTemplate(input_variables=["requirement", "test_points"],template=prompt_text,)llm = ChatOpenAI(temperature=0.2, model="gpt-3.5-turbo")testcase_chain = LLMChain(llm=llm, prompt=prompt_template)response = testcase_chain.run({"requirement": requirement,"test_points": test_points})return response # 返回的是 JSON 字符串def main():# 加载外部 Prompt 文件prompt_path = "prompts/generate_test_points.md"prompt_text = load_prompt_template(prompt_path)# 解析 Prompt 文件test_point_prompt_template = PromptTemplate(input_variables=["requirement"],template=prompt_text,)llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo")parser_chain = LLMChain(llm=llm, prompt=test_point_prompt_template)# 示例调用requirement = "用户可以使用邮箱和密码登录系统,成功后跳转到首页。若邮箱或密码错误,应显示错误信息。"test_points = parser_chain.run(requirement)print(test_points)# Step 2: 根据测试点生成测试用例test_case_json = generate_test_cases_from_points(test_points, requirement)print("📄 生成的测试用例 JSON:\\n", test_case_json)# Step 3: 导出为 Excel 文件export_test_cases_with_agent(test_case_json, filename="test_cases.xlsx")if __name__ == "__main__":main()
运行 main.py
后,Agent 会自动识别任务并调用工具进行处理。以下是执行日志:
> Entering new AgentExecutor chain...
Python REPL can execute arbitrary code. Use with caution.
Thought: Do I need to use a tool? Yes
Action: Python_REPL
Action Input: import pandas as pd
import json# Test case data
test_cases = [{"title": "邮箱密码正确时登录成功","description": "验证邮箱和密码输入正确后可登录系统","precondition": "已打开登录页面","steps": ["输入正确邮箱地址","输入正确密码","点击登录按钮"],"expected_result": "成功跳转到系统首页","actual_result": "待测试","pass_fail": "待测试"},{"title": "输入错误邮箱登录显示错误信息","description": "验证输入错误邮箱后显示错误信息","precondition": "已打开登录页面","steps": ["输入错误邮箱地址","输入正确密码","点击登录按钮"],"expected_result": "显示错误信息","actual_result": "待测试","pass_fail": "待测试"},{"title": "输入错误密码登录显示错误信息","description": "验证输入错误密码后显示错误信息","precondition": "已打开登录页面","steps": ["输入正确邮箱地址","输入错误密码","点击登录按钮"],"expected_result": "显示错误信息","actual_result": "待测试","pass_fail": "待测试"},{"title": "输入错误邮箱和密码登录显示错误信息","description": "验证输入错误邮箱和密码后显示错误信息","precondition": "已打开登录页面","steps": ["输入错误邮箱地址","输入错误密码","点击登录按钮"],"expected_result": "显示错误信息","actual_result": "待测试","pass_fail": "待测试"},{"title": "输入超长邮箱和密码登录系统","description": "验证输入超长邮箱和密码后系统能正确处理","precondition": "已打开登录页面","steps": ["输入超长邮箱地址","输入超长密码","点击登录按钮"],"expected_result": "系统能够正确处理","actual_result": "待测试","pass_fail": "待测试"},{"title": "输入空邮箱和密码登录系统","description": "验证输入空邮箱和密码后系统显示错误信息","precondition": "已打开登录页面","steps": ["清空邮箱地址","清空密码","点击登录按钮"],"expected_result": "显示错误信息","actual_result": "待测试","pass_fail": "待测试"}
]# Convert test cases to DataFrame
df = pd.DataFrame(test_cases)# Write DataFrame to Excel file
df.to_excel("test_cases.xlsx", index=False)Final Answer: The test cases have been successfully written to an Excel file named test_cases.xlsx.> Finished chain.
从日志中可以看到大模型根据input的任务进行判断需要调用工具,然后主动调用 pandas
工具完成了JSON解析和Excel的写入!
通过这个 Agent,我们实现了测试用例从自然语言生成到自动导出的全流程自动化:
- 结构化 JSON 输出:大模型负责将需求转为标准用例格式;
- 智能工具调用:Agent自动选择并执行Python写入逻辑;
- 无需硬编码写 Excel:只需提供测试点与需求,其余交给模型完成。
📎 项目地址
https://github.com/bridgeshi85/requirement-to-testcase