【发布时间】: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