Google C++测试框架系列高级篇:第二章 让GTest学习打印自定义对象

上一篇:更多关于断言的知识

原始链接:Teaching Google Test How to Print Your Values

词汇表

版本号:v_0.1

让GTest学习打印自定义对象

当一个断言比如EXPECT_EQ()失败时,GTest会打印它的参数来帮你调试。它依靠用户可扩展值打印机来实现此功能。

这个打印机了解如何打印C++的内建类型,原生数组,STL容器和任何支持"<<"操作符的类型。对于其它类型,它会打印原始的字节然后等您老自己意会。

前面提到这个打印机是可扩展的。这表明除了打印原始字节,对于你感兴趣的类型显然可以做得更好。怎么做呢?请自己实现"<<"操作符。参考以下代码:

#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

有时候这个方案也许行不通。你的团队认为使用"<<"操作符对于Bar类是个不好的风格,或者Bar类已经支持"<<"操作符但是实现了其它功能。在这种情况下,你可以定义一个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

如果"<<"操作符和PrintTo()同时被定义了,GTest会优先使用后者。这使得你可以自定义GTest如何输出你的值而不依赖于"<<"操作符的行为。

如果你想调用GTest的打印机来打印一个值x,直接调用::testing::PrintToString(x),这个函数会返回std::string。

vector<pair<Bar, int> > bar_ints = GetBarIntVector();

EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))
    << "bar_ints = " << ::testing::PrintToString(bar_ints);
posted @ 2013-11-21 18:19  移山测试工作室黑灯老师  阅读(4204)  评论(0编辑  收藏  举报
count website visits
Buy Computers