基于MCP的人工智能移动测试自动化
一种尖端的测试自动化解决方案,使用 模型上下文协议(MCP), LLM(火焰3.2:3b),以及 Appium 根据自然语言规范执行移动测试。
🎯 主要特点
- 自然语言测试规范:使用简明英语以YAML/JSON编写测试
- 无传统定位器:AI自动确定最佳元素选择器
- 交叉平台的:适用于Android和iOS
- 非交互式:CI/CD管道中的全自动执行
- 可靠性第一:语义UI分析优先于基于屏幕截图的识别
- 免费和开源:使用Llama 3.2:3b通过Ollama在本地运行
🏗️ 建筑
Jenkins Pipeline
↓
AI Test Runner (Orchestrator)
↓
┌──┴──┐
↓ ↓
LLM MCP Server
(Llama) (Appium)
↓ ↓
└──┬──┘
↓
Appium Client
↓
LambdaTest
(Devices)📋 先决条件
macOS(开发)
- macOS 12.0或更高版本(推荐使用M4芯片)
- Homebrew已安装
- Xcode命令行工具
- Node.js 18+和npm
- VS代码(推荐)
所需工具
- Ollama(在当地经营Llama)
- 附件2.x
- Git
🚀 快速开始
步骤1:克隆和设置
# Create project directory
mkdir ai-tech-app-agent
cd ai-tech-app-agent
# Initialize project (or use the artifacts provided)
npm init -y
# Install dependencies
npm install第二步:安装Ollama和Llama
# Install Ollama
brew install ollama
# Start Ollama server (keep this running)
ollama serve
# In another terminal, pull Llama model
ollama pull llama3.2:3b
# Verify installation
ollama list步骤3:安装Appium
# Install Appium globally
npm install -g appium@next
# Install required drivers
appium driver install uiautomator2 # For Android
appium driver install xcuitest # For iOS
# Verify installation
appium --version步骤4:配置环境
创建 .env 项目根目录中的文件:
# LambdaTest Configuration
LAMBDATEST_USERNAME=your_username
LAMBDATEST_ACCESS_KEY=your_access_key
LAMBDATEST_GRID_URL=https://mobile-hub.lambdatest.com/wd/hub
# Ollama/LLM Configuration
OLLAMA_BASE_URL=http://localhost:11434
LLM_MODEL=llama3.2:3b
LLM_TEMPERATURE=0.1
LLM_MAX_TOKENS=2000
# MCP Configuration
MCP_SERVER_PORT=3000
APPIUM_SERVER_URL=http://localhost:4723
# Test Configuration
DEFAULT_TIMEOUT=30000
SCREENSHOT_ON_FAILURE=true
RETRY_FAILED_STEPS=true
MAX_RETRY_ATTEMPTS=2
# Logging
LOG_LEVEL=info
LOG_DIR=./logs步骤5:构建项目
# Compile TypeScript
npm run build
# Verify build
ls -la dist/📝 编写测试规范
在中创建测试规范 tests/nlp-specs/ 目录:
示例:登录流程(login-flow.yaml)
name: Technician App Login Flow
description: Test the complete login flow with OTP verification
platform: both
setup:
- step: Launch the app
timeout: 10000
steps:
- step: Login with mobile number "112233445"
expectedOutcome: OTP screen should appear
timeout: 5000
- step: Enter OTP "1111"
expectedOutcome: Home screen should load
timeout: 5000
- step: Enable location access
expectedOutcome: Location permission granted
timeout: 5000
teardown:
- step: Close the app示例:求职流程(job-search-flow.yaml)
name: Job Search and Selection Flow
platform: both
setup:
- step: Launch the app
- step: Login with mobile number "112233445"
- step: Enter OTP "1111"
steps:
- step: Navigate to jobs tab
timeout: 5000
- step: Search for jobs near current location
timeout: 8000
- step: Select the first available job
timeout: 5000
- step: Verify job details are displayed
timeout: 3000
teardown:
- step: Return to home screen🎮 运行测试
本地执行
# Run all test specs in directory
npm run test
# Run single test spec
npm run test:single
# Or use the CLI directly
node dist/index.js run tests/nlp-specs/login-flow.yaml
# Run with app knowledge file
node dist/index.js run tests/nlp-specs/ \
--knowledge knowledge/app-knowledge.txt \
--output reports/test-report.json验证测试规范
# Validate all specs
npm run validate
# Or specific directory
node dist/index.js validate tests/nlp-specs/健康检查
# Check LLM and MCP status
npm run health🔧 与现有框架集成
要与现有的Appium框架集成,请执行以下操作:
1.重复使用设备功能
// In your AI test runner, import existing caps
import { deviceCapsHelper } from '../../../dmg.qa.test.technician-app-3/helpers/deviceCapsHelper';
// Use your existing LambdaTest configuration
const caps = deviceCapsHelper.getCapabilities('android', 'Pixel 7');2.利用页面对象知识
从现有的POM创建应用程序知识文件:
# Extract element info from your POMs
node scripts/extract-pom-knowledge.js \
--input ../dmg.qa.test.technician-app-3/pages \
--output knowledge/app-knowledge.txt3.混合方法
将现有框架作为后备方案:
// If AI fails, fall back to traditional POM
try {
await aiRunner.executeStep(step);
} catch (error) {
logger.warn('AI execution failed, using traditional POM');
await traditionalPomExecution(step);
}📊 CI/CD集成(Jenkins)
先决条件
- 为LambdaTest创建Kubernetes秘密:
kubectl create secret generic lambdatest-creds \
--from-literal=username=YOUR_USERNAME \
--from-literal=accessKey=YOUR_ACCESS_KEY- 在集群中部署Ollama服务(可选):
apiVersion: v1
kind: Service
metadata:
name: ollama-service
spec:
ports:
- port: 11434
selector:
app: ollamaJenkins管道
使用提供的 Jenkinsfile 其中包括:
- 使用Node.js和Ollama自动配置pod
- 存储库克隆
- 模型下载
- 测试执行
- 报告生成
触发器构建
# Via Jenkins UI or CLI
curl -X POST http://jenkins-url/job/ai-test-automation/build
# Or via webhook
git push origin main # If configured with GitHub webhook📈 了解测试结果
测试报告以JSON格式生成:
{
"timestamp": "2025-01-15T10:30:00Z",
"summary": {
"total": 5,
"passed": 4,
"failed": 1,
"skipped": 0
},
"results": [
{
"specName": "Login Flow",
"status": "passed",
"duration": 45000,
"steps": [...]
}
]
}🐛 故障排除
LLM没有回应
# Check if Ollama is running
ps aux | grep ollama
# Restart Ollama
pkill ollama
ollama serve
# Verify model
ollama list
ollama run llama3.2:3b "Hello"MCP连接问题
# Check Appium is running
appium --version
# Start Appium manually
appium --allow-cors --log-level info
# Check MCP-Appium installation
npm list mcp-appium测试执行失败
# Enable debug logging
export LOG_LEVEL=debug
# Check logs
tail -f logs/combined.log
# Verify device connectivity (LambdaTest)
curl -u "$LAMBDATEST_USERNAME:$LAMBDATEST_ACCESS_KEY" \
https://mobile-api.lambdatest.com/mobile-automation/api/v1/devices未执行的操作
- 检查UI上下文:确保正确捕获页面源
- 验证选择器:LLM生成的选择器可能需要调整
- 添加应用程序知识:提供有关应用程序UI模式的更多上下文
- 增加超时时间:某些操作可能需要更多时间
- 检查元素可见性:元素可能不会立即可用
📚 高级主题
自定义操作类型
扩展动作执行器以支持自定义动作:
// In mcpClient.ts
async executeCustomAction(action: CustomAction): Promise {
// Your custom logic
}微调提示
在中修改提示模板 llamaClient.ts 为了获得更好的准确性:
private buildPrompt(stepText: string, uiContext: string): string {
return `Enhanced prompt with more specific instructions...`;
}基于屏幕截图的识别
对于复杂场景,启用屏幕截图分析:
const uiContext = await mcpClient.getUIContext({
includeScreenshot: true,
screenshotAnalysis: 'vision-model'
});🤝 贡献
欢迎投稿!需要改进的地方:
- 更好地解析UI元素的XML
- 增强的错误恢复机制
- 支持更复杂的手势
- 与其他LLM提供商集成
- 性能优化
📄 许可证
MIT许可证-随意使用和修改
🙋 支持
对于问题和疑问:
- 检查故障排除部分
- 查看登录
logs/目录 - 在GitHub上打开一个问题
- 联系团队
______________________________________________________________________
备注:此解决方案将可靠性和可维护性置于执行速度之上。测试最初可能比传统脚本运行得稍慢,但提供了明显更好的可维护性和减少的不稳定性。
