如何在Google C ++testing框架中发送自定义消息?

我使用Google C ++testing框架对我的代码进行unit testing。 我使用Eclipse CDT和C ++unit testing模块进行输出分析。

以前我使用CppUnit它有macros家庭CPPUNIT * _MESSAGE可以这样调用:

CPPUNIT_ASSERT_EQUAL_MESSAGE("message",EXPECTED_VALUE,ACTUAL_VALUE) 

并允许发送自定义消息来testing输出。

有没有办法在谷歌testing输出中包含一些自定义文本?

(最好的方式,可以包括消息数据,由现有的程序读取自动化unit testing使用谷歌testing。)

gtestmacros在testing失败时返回一个用于输出诊断消息的stream。

 EXPECT_TRUE(false) << "diagnostic message"; 

在当前版本的gtest中,没有办法做到这一点。 我查看了代码,如果testing失败,则会显示唯一的文本输出(包裹在gtest“Messages”中)。

然而,在某些时候,gtest会启动printf到屏幕上,并且您可以利用上面的级别来获取与平台无关的颜色。

这是一个黑客攻击的macros来做你想做的事情。 这使用gtest内部文字着色。 当然, internal::命名空间应该听起来警告铃声,但嘿,它的工作原理。

用法:

 TEST(pa_acq,Foo) { // C style PRINTF("Hello world \n"); // or C++ style TEST_COUT << "Hello world" << std::endl; } 

输出:

输出示例

码:

 namespace testing { namespace internal { enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; extern void ColoredPrintf(GTestColor color, const char* fmt, ...); } } #define PRINTF(...) do { testing::internal::ColoredPrintf(testing::internal::COLOR_GREEN, "[ ] "); testing::internal::ColoredPrintf(testing::internal::COLOR_YELLOW, __VA_ARGS__); } while(0) // C++ stream interface class TestCout : public std::stringstream { public: ~TestCout() { PRINTF("%s",str().c_str()); } }; #define TEST_COUT TestCout() 

你应该定义如下:

 static class LOGOUT { public: LOGOUT() {} std::ostream& info() { std::cout << "[info ] "; return std::cout; } } logout; 

使用这个:

 logout.info() << "test: " << "log" << std::endl; 

请参阅Mark Lakata的回答,这里是我的方式:

第一步:创build一个头文件,例如: gtest_cout.h

码:

 #ifndef _GTEST_COUT_H_ #define _GTEST_COUT_H_ #include "gtest/gtest.h" namespace testing { namespace internal { enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; extern void ColoredPrintf(GTestColor color, const char* fmt, ...); } } #define GOUT(STREAM) \ do \ { \ std::stringstream ss; \ ss << STREAM << std::endl; \ testing::internal::ColoredPrintf(testing::internal::COLOR_GREEN, "[ ] "); \ testing::internal::ColoredPrintf(testing::internal::COLOR_YELLOW, ss.str().c_str()); \ } while (false); \ #endif /* _GTEST_COUT_H_ */ 

第二步:在gtest中使用GOUT

用法:

 #include "gtest_cout.h" TEST(xxx, yyy) { GOUT("Hello world!"); }