代码之家  ›  专栏  ›  技术社区  ›  Benjamin Buch

gtest有比较二进制的东西吗?

  •  1
  • Benjamin Buch  · 技术社区  · 8 年前

    Google Test 比较对给定对象的二进制表示进行操作的函数?

    我有两个 struct -相同类型但没有比较函数的对象。这个 结构 是一种普通的旧数据类型(POD),因此二进制比较可以工作。

    我需要这样的东西:

    struct A{
      int some_data;
    };
    
    TEST(test, case){
        A a1{0}, a2{1};
        EXPECT_BINARY_EQ(a1, a2);
    }
    

    用gtest在C++中实现这一点的最简单方法是什么。

    3 回复  |  直到 8 年前
        1
  •  2
  •   Robert Andrzejuk    8 年前

    如果您可以使用 magic_get 图书馆:

    // requires: C++14, MSVC C++17
    #include <iostream>
    #include "boost/pfr/precise.hpp"
    
    struct my_struct
    { // no operators defined!
        int    i;
        char   c;
        double d;
    };
    
    bool operator==(const my_struct& l, const my_struct& r)
    {
        using namespace boost::pfr::ops; // out-of-the-box operators for all PODs!
    
        return boost::pfr::structure_tie( l ) == boost::pfr::structure_tie( r );
    }
    
    int main()
    {
        my_struct s{ 100, 'H', 3.141593 };
        my_struct t{ 200, 'X', 1.234567 };
    
        std::cout << ( s == s ) << '\n' << ( s == t ) << "\n";
    }
    

    通过定义 operator == 可以使用Google测试中的ASSERT\u EQ:

    TEST( Test_magic_get, Test_magic_get )
    {
        my_struct s{ 100, 'H', 3.141593 };
        my_struct t{ 200, 'X', 1.234567 };
    
        //ASSERT_EQ( s, t );
        ASSERT_EQ( s, s );
    }
    
        2
  •  2
  •   Robert Andrzejuk    8 年前

    我的建议基于: http://en.cppreference.com/w/cpp/language/operators

    您可以定义 operator == 在课堂上使用 std::tie (来自元组标题)

    struct Record
    {
        std::string name;
        unsigned int floor;
        double weight;
    
        friend bool operator ==(const Record& l, const Record& r)
        {
            return   std::tie(l.name, l.floor, l.weight)
                  == std::tie(r.name, r.floor, r.weight); // keep the same order
        }
    };
    
        3
  •  0
  •   Benjamin Buch    8 年前

    我当前的解决方案:

    #include <algorithm>
    
    template < typename T >
    bool binary_eq(T const& lhs, T const& rhs){
        auto lhs_i = reinterpret_cast< char const* >(&lhs);
        auto rhs_i = reinterpret_cast< char const* >(&rhs);
        return std::equal(lhs_i, lhs_i + sizeof(T), rhs_i);
    }
    

    编辑:

    多亏了埃里克·阿拉普和弗兰克,我明白这不能通用,因为 struct 成员。在我的具体情况下,它确实有效,因为所有成员 double 's。