新增易方达接口以及添加claude技能
This commit is contained in:
@@ -0,0 +1,509 @@
|
||||
# API接口测试指南
|
||||
|
||||
接口开发完成后,需要进行系统化测试。本指南提供完整的测试流程和脚本组织方式。
|
||||
|
||||
## 测试脚本目录结构
|
||||
|
||||
在 `projects/fangjia-script/src/main/groovy/com/fangjia/script/` 下创建专门的测试包:
|
||||
|
||||
```
|
||||
opentest/ # 接口测试脚本专用包
|
||||
├── [InterfaceName]TestDataExtractor.groovy # 数据提取脚本
|
||||
├── [InterfaceName]InterfaceTest.groovy # 接口测试脚本
|
||||
└── data/ # 测试数据目录
|
||||
├── [interface]_test_data.xlsx # 测试数据(自动生成,单Sheet)
|
||||
└── [interface]_test_result.xlsx # 测试结果(自动生成,多Sheet)
|
||||
# - Sheet1: 测试结果(详细数据)
|
||||
# - Sheet2: 统计数据(汇总信息)
|
||||
```
|
||||
|
||||
**示例**:E基金地址匹配接口测试
|
||||
```
|
||||
opentest/
|
||||
├── EfundTestDataExtractor.groovy
|
||||
├── EfundInterfaceTest.groovy
|
||||
└── data/
|
||||
├── efund_test_data.xlsx # 测试数据
|
||||
└── efund_test_result.xlsx # 测试结果
|
||||
├── Sheet1: 测试结果 # 1000行详细数据
|
||||
└── Sheet2: 统计数据 # 汇总统计信息
|
||||
```
|
||||
|
||||
## 第一步:编写数据提取脚本
|
||||
|
||||
**目的**:从生产环境提取真实测试数据
|
||||
|
||||
**关键技术**:
|
||||
|
||||
### 1. 使用 Mongo3Utils 连接MongoDB(推荐)
|
||||
|
||||
```groovy
|
||||
import com.fangjia.core.Constants
|
||||
import com.fangjia.core.util.Mongo3Utils
|
||||
import com.mongodb.client.MongoCollection
|
||||
import org.bson.Document
|
||||
|
||||
// 连接206服务器
|
||||
MongoCollection<Document> coll = Mongo3Utils.getDbCollection(
|
||||
Constants.SEAWATER_MONGO_URI, // 已配置好的连接URI
|
||||
"business", // 数据库
|
||||
"open_uri_log" // 集合
|
||||
)
|
||||
```
|
||||
|
||||
### 2. 使用 projection 优化查询
|
||||
|
||||
```groovy
|
||||
// 只查询需要的字段,减少网络传输
|
||||
Document query = new Document("user_id", "xxx")
|
||||
.append("request_uri", "/api/xxx")
|
||||
|
||||
Document projection = new Document("parameter_map", 1).append("_id", 0)
|
||||
|
||||
MongoCursor<Document> cursor = coll.find(query)
|
||||
.projection(projection) // 只返回 parameter_map
|
||||
.limit(1000)
|
||||
.iterator()
|
||||
```
|
||||
|
||||
### 3. 提取测试参数
|
||||
|
||||
```groovy
|
||||
List<List<Object>> excelData = []
|
||||
excelData << ["序号", "参数1", "参数2", "参数3"] // 表头
|
||||
|
||||
int index = 0
|
||||
while (cursor.hasNext()) {
|
||||
Document doc = cursor.next()
|
||||
Document paramMap = doc.get("parameter_map", Document.class)
|
||||
|
||||
String param1 = paramMap?.getString("param1") ?: ""
|
||||
String param2 = paramMap?.getString("param2") ?: ""
|
||||
|
||||
excelData << [++index, param1, param2]
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 保存到Excel
|
||||
|
||||
```groovy
|
||||
import com.fangjia.script.util.ExcelUtils
|
||||
|
||||
// 自动确定脚本所在目录
|
||||
String scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
|
||||
String dataDir = new File(scriptDir, "data").absolutePath
|
||||
new File(dataDir).mkdirs()
|
||||
|
||||
String outputFile = "${dataDir}${File.separator}test_data.xlsx"
|
||||
ExcelUtils.write(outputFile, excelData, "测试数据")
|
||||
```
|
||||
|
||||
## 第二步:编写接口测试脚本
|
||||
|
||||
**目的**:多线程调用接口,记录结果和性能指标
|
||||
|
||||
**推荐方法**:使用 `ExcelUtils.multiThreadingModify` 工具类(自动管理线程池和进度监控)
|
||||
|
||||
### 方法一:使用 ExcelUtils.multiThreadingModify(推荐)
|
||||
|
||||
**优势**:
|
||||
- ✅ 自动管理线程池(CPU核心数×4)
|
||||
- ✅ 自动处理线程安全
|
||||
- ✅ 自动进度监控(每1000条打印进度和百分比)
|
||||
- ✅ 代码简洁,专注业务逻辑
|
||||
- ✅ 超长等待时间(30天),适合大批量测试
|
||||
|
||||
**完整示例**:
|
||||
|
||||
```groovy
|
||||
import com.fangjia.core.util.HttpRequest
|
||||
import com.fangjia.script.util.ExcelUtils
|
||||
import net.sf.json.JSONObject
|
||||
|
||||
// 1. 准备测试数据和结果Excel
|
||||
String scriptDir = new File(getClass().protectionDomain.codeSource.location.path).parent
|
||||
String dataDir = new File(scriptDir, "data").absolutePath
|
||||
String inputFile = "${dataDir}${File.separator}test_data.xlsx"
|
||||
String outputFile = "${dataDir}${File.separator}test_result.xlsx"
|
||||
|
||||
// 2. 读取所有数据(包括表头)
|
||||
List<List<Object>> allData = ExcelUtils.read(inputFile, 0, 0)
|
||||
|
||||
// 3. 修改表头,添加结果列
|
||||
allData[0] = ["序号", "参数1", "参数2", "返回字段1", "返回字段2",
|
||||
"返回字段3", "耗时(ms)", "异常信息"]
|
||||
|
||||
// 4. 为每行数据添加空的结果列
|
||||
for (int i = 1; i < allData.size(); i++) {
|
||||
List row = allData[i]
|
||||
(3..7).each { row << "" } // 添加5个结果列
|
||||
}
|
||||
|
||||
// 5. 写入初始结果文件
|
||||
ExcelUtils.write(outputFile, allData, "测试结果")
|
||||
|
||||
// 6. 使用 multiThreadingModify 多线程调用接口
|
||||
ExcelUtils.multiThreadingModify(outputFile, { List row ->
|
||||
HttpRequest request = new HttpRequest()
|
||||
long startTime = System.currentTimeMillis()
|
||||
|
||||
try {
|
||||
// 提取参数(row[0]=序号, row[1]=参数1, row[2]=参数2)
|
||||
String param1 = row[1]?.toString() ?: ""
|
||||
String param2 = row[2]?.toString() ?: ""
|
||||
|
||||
// 调用接口
|
||||
Map<String, String> params = ["param1": param1, "param2": param2]
|
||||
String response = request.get("http://localhost:9180/api/xxx", params, "UTF-8")
|
||||
long duration = System.currentTimeMillis() - startTime
|
||||
|
||||
// 解析响应
|
||||
JSONObject json = JSONObject.fromObject(response)
|
||||
Integer code = json.optInt("code")
|
||||
JSONObject result = json.optJSONObject("result")
|
||||
|
||||
if (code == 200 && result != null) {
|
||||
// 成功:填充结果列(直接修改row,工具类自动处理线程安全)
|
||||
row[3] = result.optString("field1", "")
|
||||
row[4] = result.optString("field2", "")
|
||||
row[5] = result.optString("field3", "")
|
||||
row[6] = duration
|
||||
row[7] = "" // 无异常
|
||||
} else {
|
||||
// 失败:记录错误信息
|
||||
row[6] = duration
|
||||
row[7] = "接口返回错误(code=${code}): ${json.optString('msg', '')}"
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
// 异常:记录异常信息
|
||||
long duration = System.currentTimeMillis() - startTime
|
||||
row[6] = duration
|
||||
row[7] = "异常: ${e.class.simpleName} - ${e.message}"
|
||||
}
|
||||
}, 0, "测试结果")
|
||||
|
||||
// 7. 读取结果并统计
|
||||
List<List<Object>> finalData = ExcelUtils.read(outputFile, 0, 0)
|
||||
int totalCount = finalData.size() - 1
|
||||
int successCount = 0
|
||||
int failCount = 0
|
||||
long totalTime = 0
|
||||
|
||||
// 耗时分布统计
|
||||
Map<String, Integer> timeDist = [
|
||||
"<100ms": 0,
|
||||
"100-200ms": 0,
|
||||
"200-500ms": 0,
|
||||
"500-1000ms": 0,
|
||||
">1000ms": 0
|
||||
]
|
||||
|
||||
for (int i = 1; i < finalData.size(); i++) {
|
||||
List row = finalData[i]
|
||||
String errorMsg = row[7]?.toString() ?: ""
|
||||
|
||||
if (errorMsg == "") {
|
||||
successCount++
|
||||
|
||||
// 统计耗时
|
||||
if (row[6] instanceof Number) {
|
||||
int duration = ((Number)row[6]).intValue()
|
||||
totalTime += duration
|
||||
|
||||
if (duration < 100) timeDist["<100ms"]++
|
||||
else if (duration < 200) timeDist["100-200ms"]++
|
||||
else if (duration < 500) timeDist["200-500ms"]++
|
||||
else if (duration < 1000) timeDist["500-1000ms"]++
|
||||
else timeDist[">1000ms"]++
|
||||
}
|
||||
} else {
|
||||
failCount++
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 保存统计数据到新Sheet
|
||||
List<List<Object>> statsData = []
|
||||
statsData << ["统计项", "数值"]
|
||||
statsData << ["测试时间", new Date().format("yyyy-MM-dd HH:mm:ss")]
|
||||
statsData << ["", ""]
|
||||
statsData << ["总测试数", totalCount]
|
||||
statsData << ["成功数", successCount]
|
||||
statsData << ["失败数", failCount]
|
||||
statsData << ["成功率", totalCount > 0 ? String.format('%.2f%%', successCount * 100.0 / totalCount) : '0.00%']
|
||||
|
||||
if (successCount > 0) {
|
||||
int avgTime = (totalTime / successCount).intValue()
|
||||
statsData << ["", ""]
|
||||
statsData << ["平均耗时(ms)", avgTime]
|
||||
|
||||
// 耗时分布
|
||||
statsData << ["", ""]
|
||||
statsData << ["耗时分布", "数量"]
|
||||
timeDist.each { range, count ->
|
||||
statsData << [range, count]
|
||||
}
|
||||
}
|
||||
|
||||
// 添加统计Sheet
|
||||
ExcelUtils.write(outputFile, statsData, "统计数据")
|
||||
|
||||
// 9. 控制台输出统计结果
|
||||
println "\n========== 测试完成 =========="
|
||||
println "总测试数:${totalCount}"
|
||||
println "成功数:${successCount}"
|
||||
println "失败数:${failCount}"
|
||||
println "成功率:${totalCount > 0 ? String.format('%.2f%%', successCount * 100.0 / totalCount) : '0.00%'}"
|
||||
|
||||
if (successCount > 0) {
|
||||
int avgTime = (totalTime / successCount).intValue()
|
||||
println "平均耗时:${avgTime} ms"
|
||||
|
||||
println "\n耗时分布:"
|
||||
timeDist.each { range, count ->
|
||||
if (count > 0) {
|
||||
println " ${range}: ${count} 条"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println "\n结果文件:${outputFile}"
|
||||
println " - Sheet1: 测试结果(详细数据)"
|
||||
println " - Sheet2: 统计数据(汇总信息)"
|
||||
```
|
||||
|
||||
### 方法二:手动管理线程池(适合需要自定义控制的场景)
|
||||
|
||||
<details>
|
||||
<summary>点击展开手动管理线程池的示例代码</summary>
|
||||
|
||||
```groovy
|
||||
import java.util.concurrent.*
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import com.fangjia.core.util.HttpRequest
|
||||
import net.sf.json.JSONObject
|
||||
|
||||
// 1. 读取测试数据
|
||||
List<List<Object>> testData = ExcelUtils.read(inputFile, 0, 1) // 跳过表头
|
||||
|
||||
// 2. 准备结果数据
|
||||
List<List<Object>> resultData = []
|
||||
resultData << ["序号", "参数1", "参数2", "返回字段1", "返回字段2", "耗时(ms)", "异常信息"]
|
||||
testData.each { row ->
|
||||
List newRow = [row[0], row[1], row[2]]
|
||||
(3..6).each { newRow << "" }
|
||||
resultData << newRow
|
||||
}
|
||||
|
||||
// 3. 配置线程池
|
||||
int nThread = Runtime.getRuntime().availableProcessors() * 4
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(nThread)
|
||||
AtomicInteger counter = new AtomicInteger(0)
|
||||
AtomicInteger successCounter = new AtomicInteger(0)
|
||||
|
||||
// 4. 提交任务
|
||||
testData.eachWithIndex { List testRow, int i ->
|
||||
final int rowIndex = i + 1
|
||||
executorService.submit({
|
||||
HttpRequest request = new HttpRequest()
|
||||
long startTime = System.currentTimeMillis()
|
||||
|
||||
try {
|
||||
String param1 = testRow[1]?.toString() ?: ""
|
||||
String response = request.get("http://localhost:9180/api/xxx",
|
||||
["param1": param1], "UTF-8")
|
||||
long duration = System.currentTimeMillis() - startTime
|
||||
|
||||
JSONObject json = JSONObject.fromObject(response)
|
||||
JSONObject result = json.optJSONObject("result")
|
||||
|
||||
synchronized(resultData) {
|
||||
if (json.optInt("code") == 200 && result != null) {
|
||||
resultData[rowIndex][3] = result.optString("field1", "")
|
||||
resultData[rowIndex][4] = result.optString("field2", "")
|
||||
resultData[rowIndex][5] = duration
|
||||
successCounter.incrementAndGet()
|
||||
} else {
|
||||
resultData[rowIndex][5] = duration
|
||||
resultData[rowIndex][6] = "错误: ${json.optString('msg')}"
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
synchronized(resultData) {
|
||||
resultData[rowIndex][6] = "异常: ${e.message}"
|
||||
}
|
||||
}
|
||||
|
||||
if (counter.incrementAndGet() % 100 == 0) {
|
||||
println "进度: ${counter.get()}/${testData.size()}"
|
||||
}
|
||||
} as Runnable)
|
||||
}
|
||||
|
||||
// 5. 等待完成并保存结果
|
||||
executorService.shutdown()
|
||||
executorService.awaitTermination(30, TimeUnit.MINUTES)
|
||||
ExcelUtils.write(outputFile, resultData, "测试结果")
|
||||
```
|
||||
</details>
|
||||
|
||||
## 第三步:运行测试流程
|
||||
|
||||
### 1. 构建项目
|
||||
```bash
|
||||
cd deliverables/script
|
||||
mvn clean package -Dmaven.test.skip=true
|
||||
```
|
||||
|
||||
### 2. 提取测试数据
|
||||
```bash
|
||||
groovy -cp "target/classes;target/classes/lib/*" \
|
||||
projects/fangjia-script/src/main/groovy/com/fangjia/script/opentest/XXXTestDataExtractor.groovy
|
||||
```
|
||||
|
||||
### 3. 启动fangjia-open服务
|
||||
```bash
|
||||
cd deliverables/fangjiaopen
|
||||
mvn tomcat7:run
|
||||
```
|
||||
|
||||
### 4. 运行接口测试
|
||||
```bash
|
||||
groovy -cp "target/classes;target/classes/lib/*" \
|
||||
projects/fangjia-script/src/main/groovy/com/fangjia/script/opentest/XXXInterfaceTest.groovy
|
||||
```
|
||||
|
||||
## Excel结果文件结构
|
||||
|
||||
### 测试数据Excel(单Sheet)
|
||||
|
||||
| 列 | 字段 | 说明 |
|
||||
|----|------|------|
|
||||
| A | 序号 | 1-N |
|
||||
| B | 参数1 | 接口输入参数 |
|
||||
| C | 参数2 | 接口输入参数 |
|
||||
| ... | ... | 更多参数 |
|
||||
|
||||
### 测试结果Excel(多Sheet)
|
||||
|
||||
#### 📄 Sheet1: 测试结果(详细数据)
|
||||
|
||||
| 列 | 字段 | 说明 |
|
||||
|----|------|------|
|
||||
| A | 序号 | 同测试数据 |
|
||||
| B | 参数1 | 同测试数据 |
|
||||
| C | 参数2 | 同测试数据 |
|
||||
| D | 返回字段1 | 接口返回结果 |
|
||||
| E | 返回字段2 | 接口返回结果 |
|
||||
| ... | ... | 更多返回字段 |
|
||||
| N | 耗时(ms) | 接口调用耗时 |
|
||||
| N+1 | 异常信息 | 错误时记录 |
|
||||
|
||||
#### 📊 Sheet2: 统计数据(汇总信息)
|
||||
|
||||
| 列 | 字段 | 说明 |
|
||||
|----|------|------|
|
||||
| A | 统计项 | 统计项名称 |
|
||||
| B | 数值 | 统计值 |
|
||||
|
||||
统计内容包括:
|
||||
- 测试时间(测试执行的时间戳)
|
||||
- 总测试数、成功数、失败数、成功率
|
||||
- 平均耗时(仅统计成功的请求)
|
||||
- 耗时分布(<100ms、100-200ms、200-500ms、500-1000ms、>1000ms)
|
||||
|
||||
示例:
|
||||
```
|
||||
| 统计项 | 数值 |
|
||||
|----------------|----------------------|
|
||||
| 测试时间 | 2026-02-26 14:30:15 |
|
||||
| | |
|
||||
| 总测试数 | 1000 |
|
||||
| 成功数 | 980 |
|
||||
| 失败数 | 20 |
|
||||
| 成功率 | 98.00% |
|
||||
| | |
|
||||
| 平均耗时(ms) | 245 |
|
||||
| | |
|
||||
| 耗时分布 | 数量 |
|
||||
| <100ms | 120 |
|
||||
| 100-200ms | 350 |
|
||||
| 200-500ms | 480 |
|
||||
| 500-1000ms | 30 |
|
||||
| >1000ms | 0 |
|
||||
```
|
||||
|
||||
## 测试脚本最佳实践
|
||||
|
||||
### ✅ 推荐做法
|
||||
|
||||
1. **MongoDB查询优化**
|
||||
- 使用 `Mongo3Utils` 而非旧版 `MongoUtils`
|
||||
- 使用 `projection` 只查询需要的字段
|
||||
- 使用 `Constants` 中的预定义URI
|
||||
|
||||
2. **路径处理**
|
||||
- 使用相对路径而非硬编码
|
||||
- 脚本自动识别所在目录:`new File(getClass().protectionDomain.codeSource.location.path).parent`
|
||||
|
||||
3. **多线程测试(强烈推荐)**
|
||||
- **优先使用** `ExcelUtils.multiThreadingModify` 工具方法
|
||||
- 自动管理线程池(CPU核心数×4)
|
||||
- 自动处理线程安全(无需手动 synchronized)
|
||||
- 自动进度监控(每1000条打印进度和百分比)
|
||||
- 代码简洁,专注业务逻辑
|
||||
|
||||
4. **进度监控**
|
||||
- 使用工具类自动监控(推荐)
|
||||
- 或手动实现:每100条打印进度,包含时间戳
|
||||
|
||||
5. **异常处理**
|
||||
- 捕获所有异常
|
||||
- 记录到Excel而非终止程序
|
||||
- 异常信息包含类型和消息
|
||||
|
||||
6. **统计数据保存**
|
||||
- 使用 `ExcelUtils.write(outputFile, statsData, "统计数据")` 创建统计Sheet
|
||||
- 统计内容包括:测试时间、成功率、平均耗时、耗时分布
|
||||
- 方便后续分析和生成测试报告
|
||||
|
||||
### ❌ 避免做法
|
||||
|
||||
1. ❌ 硬编码文件路径(如 `D:\test\data.xlsx`)
|
||||
2. ❌ 查询所有字段而不使用 projection
|
||||
3. ❌ 使用旧版 MongoDB API(`DBObject`、`BasicDBObject`)
|
||||
4. ❌ 单线程测试大量数据
|
||||
5. ❌ 异常时终止整个测试
|
||||
6. ❌ 手动管理线程池(除非有特殊需求,否则用工具类)
|
||||
7. ❌ 忘记处理线程安全问题(使用工具类可避免)
|
||||
|
||||
## 测试完成后的分析
|
||||
|
||||
测试完成后,Excel文件包含两个Sheet,便于多维度分析:
|
||||
|
||||
### 📊 使用统计数据Sheet快速分析
|
||||
|
||||
1. **成功率分析**:查看成功率是否 >95%
|
||||
- 低于95%需要排查失败原因
|
||||
- 在"测试结果"Sheet中过滤"异常信息"列查看失败详情
|
||||
|
||||
2. **性能分析**:查看平均耗时和耗时分布
|
||||
- 平均耗时应 <500ms(根据业务要求调整)
|
||||
- 耗时分布帮助识别性能瓶颈
|
||||
- 如果 >1000ms 的数量较多,需优化接口性能
|
||||
|
||||
3. **异常分析**:在"测试结果"Sheet中
|
||||
- 使用Excel筛选功能查看所有失败记录
|
||||
- 统计异常类型(如超时、参数错误、业务异常等)
|
||||
- 针对高频异常进行优化
|
||||
|
||||
4. **数据质量分析**:在"测试结果"Sheet中
|
||||
- 检查返回字段的完整性(是否有大量空值)
|
||||
- 检查价格、匹配级别等核心字段的填充率
|
||||
- 对比不同匹配级别的数据分布
|
||||
|
||||
### 💡 建议
|
||||
|
||||
- 将统计数据Sheet制作成Excel图表(饼图、柱状图)便于可视化分析
|
||||
- 保存多次测试结果,对比性能变化趋势
|
||||
- 将测试报告作为接口验收的依据
|
||||
Reference in New Issue
Block a user