Teaching Google Test How to Print Your Values
自定义打印的消息
When a test assertion such as EXPECT_EQ
fails, Google Test prints the argument values to help you debug. It does this using a user-extensible value printer.
当一个测试断言失败的时候,gtest会打印调用宏(比如EXPTECT_EQ()
)的参数,这样可以帮助定位错误。这其实使用了一种“可用户扩展的打印”机制。
This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the <<
operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out.
这种打印机制,可以打印C++内置的类型、STL容器和任何支持流操作的类型,对于其他的类型,会打印它的原始字节,这样用户可以自己计算它们的值。
As mentioned earlier, the printer is extensible. That means you can teach it to do a better job at printing your particular type than to dump the bytes. To do that, define <<
for your type:
就像以前提到的,这种打印机制是“可扩展的”。这意味着你可以自己定义或是重载流操作符“<<
”,来打印自己定制的消息及格式。这可比打印原始字节易读多了。下面是一个例子:
#include <iostream>
namespace foo {
class Bar { ... }; // We want Google Test to be able to print instances of this.
// It's important that the << operator is defined in the SAME
// namespace that defines Bar. C++'s look-up rules rely on that.
::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {
return os << bar.DebugString(); // whatever needed to print bar to os
}
} // namespace foo
Sometimes, this might not be an option: your team may consider it bad style to have a <<
operator for Bar
, or Bar
may already have a <<
operator that doesn’t do what you want (and you cannot change it). If so, you can instead define a PrintTo()
function like this:
但是,有时候你可能并不能这么做:如果你的对象本身有了<<
操作,但是这个操作的风格很不好或者这种输出风格并不是你想要的。这个时候,你可以用PrintTo()
函数来代替流输出操作:
#include <iostream>
namespace foo {
class Bar { ... };
// It's important that PrintTo() is defined in the SAME
// namespace that defines Bar. C++'s look-up rules rely on that.
void PrintTo(const Bar& bar, ::std::ostream* os) {
*os << bar.DebugString(); // whatever needed to print bar to os
}
} // namespace foo
If you have defined both <<
and PrintTo()
, the latter will be used when Google Test is concerned. This allows you to customize how the value appears in Google Test’s output without affecting code that relies on the behavior of its <<
operator.
如果同时定义了<<
和PrintTo()
,那么只有PrintTo()
是有效的,这样在自定义gtest输出的同时,又不影响代码中其他依赖于<<
操作符的行为。
If you want to print a value x
using Google Test’s value printer yourself, just call ::testing::PrintToString(
x)
, which returns an std::string
:
::testing::PrintToString(
x)
可以把_x_
转换成std::string
输出 。
vector<pair<Bar, int> > bar_ints = GetBarIntVector();
EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
<< "bar_ints = " << ::testing::PrintToString(bar_ints);