有没有测试比较二进制的东西?
Has gtest something that compares binary?
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
的。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 有根的二进制搜索树.保留与其父级的链接
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 为什么二进制搜索在我的测试中不起作用
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- 测试树是否为二进制搜索树
- 有没有测试比较二进制的东西?
- 所有测试用例都将小数点转换为二进制数
- 如何在 postgreSQL 中调试回归测试二进制pg_regress
- 一半填充二进制搜索树进行测试的最佳方法
- 二进制搜索测试柜不返回值
- 无法将库与CMAKE中的测试二进制链接
- 在 Google 的C++测试框架中为多个单元测试创建一个二进制文件
- 二进制搜索程序。在应用测试用例时给出正确的输出仍然显示" "超出时间限制" "错误
- cmake - 单元测试++链接单元测试二进制文件失败
- 使用带有g++和gtest的scons制作单元测试二进制文件
- 如何实现返回二进制数据的简单C函数的单元测试
- 对二进制搜索树进行单元测试
- 我可以将多个BOOST单元测试链接到一个测试二进制文件中吗