第二篇:《测试指挥官:可视化单题自测框架(含 assert 实操)》

📅 2026/7/18 5:06:56 👁️ 阅读次数 📝 编程学习
第二篇:《测试指挥官:可视化单题自测框架(含 assert 实操)》

一、趣味开篇

原生assert只能默默报错,无法直观看到每组用例状态。我们打造专属测试指挥官,融合assert基础逻辑,封装可视化校验工具,完整跑完所有用例,清晰打印每一组用例的成功 / 失败状态,适配单题 10 组以内测试场景。

二、原生 assert 完整实操演示(拆分原第一篇实操内容)

1. assert 基础代码示例(登录逻辑)

cpp

运行

#include <iostream> #include <string> #include <cassert> using namespace std; // 待测试业务函数:账号登录判断 string login(string username, string password) { if (username == "admin" && password == "123456") return "登录成功"; else return "账号或密码错误"; } // assert原生自动测试函数 void testLoginAssert() { // 标准正常用例 assert(login("admin", "123456") == "登录成功"); // 错误密码异常用例 assert(login("admin", "666888") == "账号或密码错误"); // 空用户名边界用例 assert(login("", "123456") == "账号或密码错误"); // 空密码边界用例 assert(login("testuser", "") == "账号或密码错误"); cout << "✅ assert全部校验完成,无逻辑漏洞" << endl; } int main() { testLoginAssert(); return 0; }
2. assert 踩坑实操总结
  1. 成功无输出:全部用例通过不会打印任何日志,新手容易误以为代码未执行;
  2. 中断缺陷:任意一条用例失败,程序直接退出,剩余用例不会执行;
  3. 关闭断言实操:在所有头文件最上方添加#define NDEBUG,屏蔽全部 assert。

三、自定义指挥官 check 工具(解决 assert 短板)

封装check函数,失败不终止程序,可视化打印通过 / 失败日志,自定义场景描述:

cpp

运行

#include <iostream> #include <string> using namespace std; // 测试指挥官核心校验工具 void check(bool judgeRes, string caseDesc) { if (judgeRes) { cout << "[✅ 通过] " << caseDesc << endl; } else { cout << "[❌ 失败] " << caseDesc << endl; } } // 待测试函数:会员等级判定 string getVip(int consume) { if (consume > 1000) return "VIP会员"; else return "普通用户"; } // 指挥官批量调度测试用例 void testVipCommander() { check(getVip(1001) == "VIP会员", "用例1:消费超1000,VIP"); check(getVip(999) == "普通用户", "用例2:消费不足1000,普通用户"); check(getVip(1000) == "普通用户", "用例3:临界边界1000"); check(getVip(0) == "普通用户", "用例4:零消费极端边界"); } int main() { testVipCommander(); return 0; }

四、算法笔试专用数值模板(股票例题)

针对股票、最长回文、水果礼包等数值返回类算法,封装专用数值校验接口,展示预期值与实际值差异:

cpp

运行

#include <iostream> #include <algorithm> using namespace std; // 待测试算法:单次买卖股票最大收益 int maxProfit(int n, int prices[]) { int minPrice = prices[0]; int ans = 0; for (int i = 1; i < n; i++) { ans = max(ans, prices[i] - minPrice); minPrice = min(minPrice, prices[i]); } return ans; } // 数值算法专用指挥官校验函数 void testNumCase(int dataLen, int arr[], int expectAns, string caseName) { int realAns = maxProfit(dataLen, arr); if (realAns == expectAns) cout << "[✅ 通过] " << caseName << " 预期收益:" << expectAns << endl; else cout << "[❌ 失败] " << caseName << " 预期:" << expectAns << " 实际运行结果:" << realAns << endl; } void stockTestCommander() { // 官方样例场景 int sample1[] = {8,9,2,5,4,7,1}; testNumCase(7, sample1, 5, "官方样例ababc收益"); // 持续下跌无盈利极端场景 int sample2[] = {9,7,5,3,1}; testNumCase(5, sample2, 0, "全下跌股票,无盈利"); // 仅一天股票边界场景 int sample3[] = {4}; testNumCase(1, sample3, 0, "仅1天,无法完成买卖"); } int main() { stockTestCommander(); return 0; }

第二篇思维导图

谢谢