• 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);
  • 相关阅读:
    Swift代码实现加载WEBVIEW
    android 图片压缩
    Android图片压缩(质量压缩和尺寸压缩)
    Android压缩图片到100K以下并保持不失真的高效方法
    android图片压缩的3种方法实例
    几种颜色模型的转换公式
    RGB HSV HLS三种色彩模式转换(C语言实现)
    由RGB到HSV颜色空间的理解
    BZOJ 1052 HAOI2007 覆盖问题 二分法答案+DFS
    插入排序算法
  • 原文地址:https://www.cnblogs.com/panda_lin/p/gtest_advanced_ch_02_teaching_google_test_how_to_print_your_values.html
Copyright © 2020-2023  润新知