首页 > 解决方案 > 如何用 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;
}

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

标签: c++unit-testingtesting

解决方案


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

#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();
}

推荐阅读