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

新手上路,请多包涵

我从未为我的 C++ 程序编写过单元测试或任何测试。我只知道它们旨在测试函数/程序/单元是否完全按照您的想法执行,但我不知道如何编写。

任何人都可以帮我测试我的示例函数吗?

 void 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;
}

我不是要一个框架。我只是不知道从哪里以及如何开始。

  • 我必须使用什么语法?
  • 是否因我使用的框架而异?
  • 我是为我的代码的每个函数和所有分支编写测试,还是只为我认为可能比较棘手的那些编写测试?

原文由 tinkerbell 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 265
1 个回答

没有框架

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

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

使用 Catch2 框架

这就是您使用 Catch2 编写相同测试的方式,这是一个简单的仅标头框架:

主文件

#define CATCH_CONFIG_RUNNER
#include "Catch2/catch.hpp"

#include <iostream>

int main(int argc, char* argv[])
{
    const int retval = Catch::Session().run(argc, argv);
    std::cin.get();

    return retval;
}

测试.cpp

 #include "Catch2/catch.hpp"

// Assuming the function under test is in this file
#include "function1.h"

TEST_CASE("function1", "function1")
{
    REQUIRE_FALSE(function1(0));
    REQUIRE_FALSE(function1(5));
    REQUIRE(function1(10));
}

注意:这些文件都不需要头文件。您可以简单地将 cpp 文件添加到您的项目中,只要它有 TEST_CASE ,它就会被执行。

原文由 VLL 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题