我喜欢为包含一些浮点值的结构编写匹配器:
struct Point3D
{
float x;
float y;
float z;
}
class Interface
{
virtual void SetPoint(Point3D point) = 0;
}
class MockInterface:
public Interface
{
MOCK_METHOD1(SetPoint, void(Point3D point));
}
MATCHER_P(Point3DEq, point, "Comparison of a Point3D")
{
return point.x == arg.x && point.y == arg.y && point.z == arg.z;
}
TEST(Point3DComparison, TestIfPoint3DAreEqual)
{
MockInterface interfaceFake;
Point setPoint = { 1.0, 1.0, 1.0 }
EXPECT_CALL(interfaceFake, SetPoint(Point3DEq(setPoint)).WillOnce(Return());
}
我不喜欢这个Matcher,因为他并不尊重良好的浮动比较。我想用gmock或gtest的浮动比较来编写一个Matcher。看起来应该类似。
MATCHER_P(Point3DEq, point, "Comparison of a Point3D")
{
return EXPECT_THAT(point.x, FloatEq(arg.x) && EXPECT_THAT(point.y, FloatEq(arg.y) && EXPECT_THAT(point.z, FloatEq(arg.z);
}
问题是EXPECT_THAT没有返回任何布尔值。使用gmock和gtest的功能有没有一个很好的干净方法?
答案 0 :(得分:1)
好的方法是忘记MATCHER_P
...
使用::testing::AllOf
- 并使用gmock中的正确匹配器 - 如提到的FloatEq
/DoubleEq
- 请参阅:
auto Point3DEq(Point3D const& p_expected)
{
using namespace testing;
return AllOf(Field(&Point3D::x, DoubleEq(p_expected.x)),
Field(&Point3D::y, DoubleEq(p_expected.y)),
Field(&Point3D::z, DoubleEq(p_expected.z)));
}