2016-10-28 41 views
4

如果我想编写自己的test.cpp来检查另一个.cpp文件是否以我希望输出的方式输出,是否有没有明确地打印它?C++单元测试检查输出是否正确

换句话说,就是那里

assert(output_of_file_being_tested, "this is the correct output"); 

任何这样的地方output_of_file_being_tested是什么,应该是“COUT”主编。

+1

你可以做类似这样的事情:http://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files –

+2

如果你避免写'std :: cout'直接写入'std :: ostream&'参考。然后当应用程序通过'std :: cout'时,测试框架可以传递'std :: ostringstream'对象。 – Galik

回答

6

解决方案不是对输出流进行硬编码。以某种方式将对std::ostream的引用传递给您的代码,并使用std::stringstream收集测试环境中的输出。

例如,这是你的 “另一个的.cpp” 文件的内容:

void toBeTested(std::ostream& output) { 
     output << "this is the correct output"; 
} 

所以在生产/释放的代码,你可以通过std::cout的功能:

void productionCode() { 
     toBeTested(std::cout); 
} 

而在测试环境中,您可能会将输出收集到sting流中并检查其是否正确:

// test.cpp 
#include <sstream> 
#include <cassert> 

void test() { 
     std::stringstream ss; 
     toBeTested(ss); 
     assert(ss.str() == "this is the correct output"); 
}