本主题说明如何让测试检查发送到标准输出或标准错误流的数据。这是通过与 C++test Stream API 交互完成的,该 API 专为使用标准输入/输出流而设计。该 API 允许对流进行操作和内容验证。
各节内容包括:
使用 C++test Stream API
要使测试检查发送到标准输出或标准错误流的数据,请执行以下操作:
要在测试用例执行之前重定向流,请使用以下功能之一:
CppTest_StreamRedirect* CppTest_RedirectStdOutput() CppTest_StreamRedirect* CppTest_RedirectStdError()
CppTest_StreamRedirect* CppTest_RedirectStdOutput()和CppTest_StreamRedirect* CppTest_RedirectStdError()返回指向特殊内部 C++test 结构或 NULL 的指针(如果发生错误)。该指针可以稍后在其他流重定向功能中使用,如图所示Example。要将流的内容与以空值终止的字符串或数据缓冲区进行比较,请使用以下函数:
CppTest_StreamCompare(CppTest_StreamRedirect* redirect, const char* value); CppTest_StreamNCompare(CppTest_StreamRedirect* redirect, const char* value, unsigned int size);
如果值与流值匹配,则两个函数均返回 0;如果值小于流值,则返回小于零的整数;如果值大于流值,则返回大于零的整数。
CppTest_StreamCompare行为类似于 strcmp。要使用函数从流中获取整个数据缓冲区,请使用
char* CppTest_StreamReadData(CppTest_StreamRedirect* redirect, unsigned int* len);该函数将指针与流中的数据一起返回到缓冲区。缓冲区的大小将在len参数中传递回去。缓冲区是使用malloc函数分配的。您有责任释放此缓冲区。要设置输入流的值,请使用以下初始化函数:
CppTest_StreamRedirect* CppTest_RedirectStdInput(const char* value); CppTest_StreamRedirect* CppTest_RedirectNStdInput(const char* value, unsigned int size)
这些函数将输入流设置为提供的字符串的值(在第二种情况下使用 N 个字符)。
在测试用例结束时,将 C++test 内部流重置为默认状态
void CppTest_StreamReset(CppTest_StreamRedirect* redirect);
示例
/* CPPTEST_TEST_CASE_BEGIN foo_test */
void TestSuite::foo_test()
{
/* Pre-condition initialization */
CppTest_StreamRedirect* output_stream = CppTest_RedirectStdOutput();
/* Tested function call */ ::foo();
/* Post-condition check */
/* This assert validates that "Output string" is put by foo() on standard output. */
CPPTEST_ASSERT(0 == CppTest_StreamCompare(output_stream, "Output string"));
CppTest_StreamReset(output_stream);
}
/* CPPTEST_TEST_CASE_END foo_test */
/* CPPTEST_TEST_CASE_BEGIN bar_test */
void TestSuite_a_0::bar_test()
{
/* Pre-condition initialization */
CppTest_StreamRedirect* input_stream = CppTest_RedirectStdInput("Hello World!\n");
/* Tested function call */
/* bar() reads standard input and returns the string */
std::string ret = ::bar();
/* Post-condition check */
CPPTEST_ASSERT(ret == "Hello World!");
CppTest_StreamReset(input_stream);
}
/* CPPTEST_TEST_CASE_END bar_test */