简体   繁体   English

C++ 标准的单元测试

[英]Unit tests for C++ criterion

I'm trying to make unit tests with criterion for my C++ code but I can't figure out how to test a function that only print and do not return anything.我正在尝试使用我的 C++ 代码的标准进行单元测试,但我不知道如何测试仅打印且不返回任何内容的 function。 Here's what I tried:这是我尝试过的:

//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);
}

But now that I'm here I don't know what to use to check if the print is correct.但是现在我在这里,我不知道用什么来检查打印是否正确。

With gtest, I think this can help you使用gtest,我认为这可以帮助您

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

refer from: How to capture stdout/stderr with googletest?参考: 如何使用 googletest 捕获 stdout/stderr?

The other answer shows how to use a googletest facility.另一个答案显示了如何使用 googletest 工具。 However, in general when your code is difficult to test, then that is a code smell.但是,一般来说,当您的代码难以测试时,那就是代码异味。 Consider this simpler example:考虑这个更简单的例子:

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

This is much easier to test when don't use std::cout directly, but pass the stream to be used as parameter:当不直接使用std::cout时,这更容易测试,而是通过 stream 用作参数:

#include <iostream>
#include <sstream>

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

In general, I do not recommend to use std::cout directly for anything but small toy programs.一般来说,我不建议将std::cout直接用于小玩具程序以外的任何东西。 You never know if later you want to write to a file or some other stream.您永远不知道以后是否要写入文件或其他 stream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM