c++ - 如何用 C++ 编写单元测试?
问题描述
我从未为我的 c++ 程序编写过单元测试或任何测试。我知道它们只是为了测试函数/程序/单元是否完全按照您的想法执行,但我不知道如何编写。
任何人都可以帮我测试我的示例函数吗?测试框架意味着什么?我是为我的代码的每个函数和所有分支编写测试,还是只为我认为可能比较棘手的那些编写测试?
doMode(int i) {
int a = fromString<int>(Action[i][1]);
int b = fromString<int>(Action[i][2]);
std::cout << "Parameter:\t" << a << "\t" << b << "\t" << std::endl;
Sleep(200);
return;
}
编辑:我不是要一个框架。或更好:可能这与我的问题有关。我只是不知道从哪里以及如何开始。我必须使用什么语法?是否因我使用的框架而异?
解决方案
这就是在没有框架的情况下编写单元测试的方式。
#include <iostream>
// Function to test
bool function1(int a) {
return a > 5;
}
// If parameter is not true, test fails
// This check function would be provided by the test framework
#define IS_TRUE(x) { if (!(x)) std::cout << __FUNCTION__ << " failed on line " << __LINE__ << std::endl; }
// Test for function1()
// You would need to write these even when using a framework
void test_function1()
{
IS_TRUE(!function1(0));
IS_TRUE(!function1(5));
IS_TRUE(function1(10));
}
int main(void) {
// Call all tests. Using a test framework would simplify this.
test_function1();
}
推荐阅读
- python - 使用 sklearn.cross_validation.KFold() 在 Python 中使用 train_index 创建 K 数据帧,Kfold 交叉验证的 test_index
- javascript - 如何在具有 Crome 或 Microsoft Edge 的本地计算机上使用 localStorage
- linux - 在 bash 脚本中执行用户的输入
- flutter - RaisedButton 的 onPressed 事件不显示小部件
- ios - 视频,上传到 S3 存储桶,而不是通过 iOS 应用程序中的 url 播放
- ios - swift Xcode中prepare()的反面是什么
- google-maps - 以 Flutter 银色或黑白风格设计 Google 地图
- azure-active-directory - 将 Azure Active Directory 与 Keycloak 集成时是否需要高级版?
- mysql - 获取外键的计数和分组
- c++ - 构建多个线程以获得最佳性能的正确方法是什么?