c++ - 如何在 C++ 中编写单元测试?

标签 c++ unit-testing testing

关闭。这个问题需要更多focused .它目前不接受答案。












想改善这个问题吗?更新问题,使其仅关注一个问题 editing this post .

3年前关闭。




Improve this question




我从未为我的 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();
}

关于c++ - 如何在 C++ 中编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52273110/

相关文章:

c++ - 内存泄漏问题

flutter - 如何在 Dart 中模拟 File 实例

testing - 在测试中获取 CSRF token

java - 在 switch 语句中测试(junit)默认情况?

laravel - 功能测试和浏览器测试之间的区别

c++ - _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) C++ 文件

c++ - 从 void* 转换为 Base* 是任何 Derived<I>*

c++ - 如何制作像 R f<void(int)>(args...) 这样的模板函数

python - 模拟 Django 模型和 save()

c# - 如何测试包含 Application.Current 的方法