【问题标题】:Unit tests for C++ criterionC++ 标准的单元测试
【发布时间】:2022-01-20 09:40:08
【问题描述】:

我正在尝试使用 C++ 代码的标准进行单元测试,但我不知道如何测试仅打印且不返回任何内容的函数。这是我尝试过的:

//the function to test

#include <iostream>
#include <fstream>

void my_cat(int ac, char **av)
{
    if (ac <= 1)
        std::cout << "my_cat: Usage: ./my_cat file [...]" << std::endl;
    for (unsigned i = 1; i < ac; i += 1) {
        std::ifstream file (av[i]);
        if (file.fail()) {
            std::cout << "my_cat: ";
            std::cout << av[i];
            std::cout << ": No such file or directory" << std::endl;
        }
        else if (file.is_open()) {
            std::cout << file.rdbuf() << std::endl;
        }
        file.close();
    }
}
//the test
#include  <criterion/criterion.h>
#include  <criterion/redirect.h>

void my_cat(int ac, char **av);

Test(mycat, my_cat)
{
    char *av[] = {"./my_cat", "text.txt"};
    my_cat(2, av);
}

但现在我在这里我不知道用什么来检查打印是否正确。

【问题讨论】:

  • 问题是您希望测试逻辑的哪一部分? IMO 的主要问题是这个功能应该被分解成更小的部分。这样操作后测试一下就容易了。
  • 我知道你是对的

标签: c++ unit-testing


【解决方案1】:

使用 gtest,我认为这可以帮助您

testing::internal::CaptureStdout();
std::cout << "My test";
std::string output = testing::internal::GetCapturedStdout();

参考来自:How to capture stdout/stderr with googletest?

【讨论】:

    【解决方案2】:

    另一个答案显示了如何使用 googletest 工具。但是,通常当您的代码难以测试时,这就是代码异味。考虑这个更简单的例子:

    void foo(){
        std::cout << "hello";
    }
    

    当不直接使用std::cout,而是将流作为参数传递时,这更容易测试:

    #include <iostream>
    #include <sstream>
    
    void foo(std::ostream& out){
        out << "hello";
    }
        
    int main() {
        std::stringstream ss;
        foo(ss);
        std::cout << (ss.str() == "hello");
    }
    

    一般来说,我不建议将std::cout 直接用于小玩具程序以外的任何东西。您永远不知道以后是否要写入文件或其他流。

    【讨论】:

      猜你喜欢
      • 2010-10-05
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多