有没有测试比较二进制的东西?

Has gtest something that compares binary?

本文关键字:二进制 测试 比较 有没有      更新时间:2023-10-16

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

我有两个相同类型的struct对象,但没有比较功能。struct是普通旧数据类型 (POD(,因此二进制比较将起作用。

我需要这样的东西:

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

在与 gtest C++中做到这一点的最简单方法是什么。

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

您可以使用std::tie(从元组标头(定义类的operator ==

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
}
};

如果您可以使用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 ==ASSERT_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 );
}

我当前的解决方案:

#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);
}

编辑:

感谢Erik Alapää和Frank,我知道这不能普遍工作,因为struct成员的填充。在我的特定情况下,它确实有效,因为所有成员都是double的。