当测试断言(例如 EXPECT_EQ
)失败时,googletest 会输出参数值以帮助您进行调试。
它使用用户可扩展值的打印器执行此操作。
该打印器知道如何打印内置的 C++ 类型,本机数组,STL 容器以及任何支持 <<
操作符的类型。
对于其他类型,它将在值中打印原始字节,并希望用户可以理解它。
如前所述,打印机是可扩展的。这意味着您可以教它在打印特定类型方面比转储字节更好。
为此,请为您的类型定义 <<
:
#include <ostream>
namespace foo {
class Bar { // We want googletest to be able to print instances of this.
...
// Create a free inline friend function.
friend std::ostream& operator<<(std::ostream& os, const Bar& bar) {
return os << bar.DebugString(); // whatever needed to print bar to os
}
};
// If you can't declare the function in the class 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20