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

tin*_*ell 4 c++ testing unit-testing

我从未为我的 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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我不是在要求一个框架。或者更好:这可能与我的问题有关。我只是不知道从哪里开始以及如何开始。我必须使用的语法是什么?是否因我使用的框架而异?

vll*_*vll 6

这就是您在没有框架的情况下编写单元测试的方式。

#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();
}
Run Code Online (Sandbox Code Playgroud)


Fre*_*shD 1

您确实应该阅读一些关于单元测试的介绍(例如这个)。但是为了给您一些提示并回答您的一些问题。

选择测试框架:
您可以选择任何您喜欢的框架,但如果您不知道选择哪个,我建议尝试GoogleTest,它非常流行并且有很好的文档。

我是为代码的每个函数和所有分支编写测试,还是只为我认为可能棘手的函数编写测试?

您应该为代码的每个函数和每个分支编写测试。