非常简单的测试库

Extremely simple test library

本文关键字:测试 简单 非常      更新时间:2023-10-16

是否存在具有友好许可证的易于嵌入的C++测试库?我想要一个单头文件。没有.cpp文件,没有5 PB的include。因此,CppUnit和Boost.Test都已退出。

基本上,我只想把单个文件放到项目树中,包括它,并能够编写

 testEqual(a,b)

看看它是否失败。我会使用assert,但它在非调试模式下不工作,也不能打印ab的值,在重写assert之前,我宁愿搜索现有的库。

我很想说"自己写",这就是我所做的。另一方面,您可能希望重用我所写的内容:test_util.hpp和test_util.cpp。将cpp文件中的一个定义内联到hpp文件中很简单。麻省理工学院。我也把它粘贴到下面的答案中。

这可以让您编写这样的测试文件:

#include "test_util.hpp"
bool test_one() {
    bool ok = true;
    CHECK_EQUAL(1, 1);
    return ok;
}
int main() {
    bool ok = true;
    ok &= test_one();
    // Alternatively, if you want better error reporting:
    ok &= EXEC(test_one);
    // ...
    return ok ? 0 : 1;
}

在测试目录中浏览以获得更多灵感。


// By Magnus Hoff, from http://stackoverflow.com/a/9964394
#ifndef TEST_UTIL_HPP
#define TEST_UTIL_HPP
#include <iostream>
// The error messages are formatted like GCC's error messages, to allow an IDE
// to pick them up as error messages.
#define REPORT(msg) 
    std::cerr << __FILE__ << ':' << __LINE__ << ": error: " msg << std::endl;
#define CHECK_EQUAL(a, b) 
    if ((a) != (b)) { 
        REPORT( 
            "Failed test: " #a " == " #b " " 
            "(" << (a) << " != " << (b) << ')' 
        ) 
        ok = false; 
    }
static bool execute(bool(*f)(), const char* f_name) {
    bool result = f();
    if (!result) {
        std::cerr << "Test failed: " << f_name << std::endl;
    }
    return result;
}
#define EXEC(f) execute(f, #f)
#endif // TEST_UTIL_HPP

尝试谷歌测试https://github.com/google/googletest/

它真的很轻,跨平台和简单。