標準出力または標準エラー出力に送られるデータをテストで検証したい場合、C/C++test Stream API を使って検証できます。C/C++test Stream API は標準の入出力ストリームを使用するように設計されており、ストリームの操作とストリームの内容の検証を実行できます。
このセクションの内容:
C/C++test Stream API の使用
標準出力または標準エラー出力に送られるデータをテストで検証するには、次の操作を行います。
テスト ケースの実行前にストリームをリダイレクトするには、次のいずれかの関数を使用します。
CppTest_StreamRedirect* CppTest_RedirectStdOutput() CppTest_StreamRedirect* CppTest_RedirectStdError()
CppTest_StreamRedirect* CppTest_RedirectStdOutput()およびCppTest_StreamRedirect* CppTest_RedirectStdError()はどちらも特別な内部 C/C++test 構造へのポインターを返します (エラーの場合は NULL を返します)。「例」にあるように、このポインターは後で別のストリーム リダイレクト関数で使用できます。ストリームの内容を NULL 終了文字列またはデータ バッファーと比較するには、次の関数を使用します。
CppTest_StreamCompare(CppTest_StreamRedirect* redirect, const char* value); CppTest_StreamNCompare(CppTest_StreamRedirect* redirect, const char* value, unsigned int size);
どちらの関数も、value がストリーム値に一致した場合は 0 を返し、value がストリーム値より小さい場合は負の整数を返し、value がストリーム値よりも大きい場合は正の整数を返します。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)
これらの関数は指定の文字列の値を入力ストリームに設定します。引数を 2 つ指定した後者の呼び出し方の場合、指定文字列中の n 文字が使用されます。テスト ケースの最後で C/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 */