我正在嘗試使用 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);
}
但是現在我在這里,我不知道用什么來檢查列印是否正確。
uj5u.com熱心網友回復:
使用gtest,我認為這可以幫助您
testing::internal::CaptureStdout();
std::cout << "My test";
std::string output = testing::internal::GetCapturedStdout();
參考:如何使用 googletest 捕獲標準輸出/標準錯誤?
uj5u.com熱心網友回復:
另一個答案顯示了如何使用 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直接用于小玩具程式以外的任何東西。您永遠不知道以后是否要寫入檔案或其他流。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417406.html
標籤:
