使Google Test Framework输出用户定义的类型

时间:2012-11-27 16:07:01

标签: c++ unit-testing namespaces operator-overloading

我想在上述测试框架中输出我的类型。 Google clearly states这是可能的。

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:

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
我似乎已经这样做了。但是在尝试编译时,我得到了以下内容:

error: no match for ‘operator<<’ in ‘* os << val’ /usr/include/c++/4.4/ostream:108: note: candidates are:

接下来是一长串提案,最后我的重载operator<<

std::ostream& Navmii::ProgrammingTest::operator<<(std::ostream&, Navmii::ProgrammingTest::AsciiString&)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您似乎已为非const operator<<对象定义了AsciiString。无论Google试图打印什么,都可能是常量。将第二个参数作为const引用传递,因为您不应该修改您打印的值:

std::ostream& Navmii::ProgrammingTest::operator<<(
  std::ostream&,
  Navmii::ProgrammingTest::AsciiString const&);

更接近匹配链接文档中的代码。但是,问题中的引文中省略了该部分。

问题引用PrintTo示例。该代码很好,但我不认为这是你在自己的代码中真正做到的。如文档所述,如果您不想提供PrintTo,或者您的类的operator<<不适合单元测试期间的调试输出,则可以使用operator<<