如何编写测试代码验证响应体Pretty区域行数固定为36行?
验证响应体行数为36的测试代码示例
根据不同的测试工具,这里提供几种常用的实现方案:
Postman 测试脚本
在Postman的「Tests」标签页中添加以下脚本,即可自动校验响应体的行数:
// 将响应文本按换行符分割为行数组 const responseLines = pm.response.text().split('\n'); // 断言行数等于36 pm.test("响应体行数必须为36", function () { pm.expect(responseLines.length).to.eql(36); });
注意:如果响应末尾存在空行导致计数偏差,可以添加过滤逻辑:const responseLines = pm.response.text().split('\n').filter(line => line.trim() !== '');
Node.js(Supertest + Jest)
如果是在Node.js环境下做API测试,结合Supertest和Jest的实现代码如下:
const request = require('supertest'); const app = require('./your-app'); // 替换为你的应用入口文件 test('接口响应行数为36', async () => { const res = await request(app).get('/target-endpoint'); // 替换为你的接口路径 const responseLines = res.text.split('\n'); // 如需过滤空行,替换为:const responseLines = res.text.split('\n').filter(line => line.trim() !== ''); expect(responseLines.length).toBe(36); });
Python(Requests + Pytest)
用Python的Requests库结合Pytest框架的实现示例:
import requests def test_response_line_count(): res = requests.get("https://your-api-domain.com/target-path") # 替换为你的接口URL response_lines = res.text.split('\n') # 过滤空行的话使用:response_lines = [line for line in res.text.split('\n') if line.strip()] assert len(response_lines) == 36
内容的提问来源于stack exchange,提问作者chokachi
相关产品推荐
相关产品推荐

