首页 技术 正文
技术 2022年11月14日
0 收藏 372 点赞 4,699 浏览 1265 个字

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

原始链接: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);
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,092
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,568
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,416
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,189
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,825
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,908