匹配googlemock中自定义类型的参数

Matching arguments of custom type in googlemock

本文关键字:参数 类型 自定义 googlemock 匹配      更新时间:2023-10-16

我在使用google mock匹配函数参数到特定对象时遇到问题。

考虑以下代码:

class Foo
{
public:
    struct Bar
    {
        int foobar;
    }
    void myMethod(const Bar& bar);
}
现在我有一些测试代码,它看起来像这样:
Foo::Bar bar;
EXPECT_CALL(fooMock, myMethod(Eq(bar));

所以我想确保当Foo::myMethod被调用时,参数看起来像我的本地实例化的bar对象。

当我尝试这种方法时,我得到如下错误消息:

gmock/gmock-matchers.h(738): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const Foo::Bar' (or there is no acceptable conversion)

我试着玩定义运算符==和!=(至少==两者作为自由函数的成员),使用Eq(ByRef(bar)),但我无法解决这个问题。唯一有用的是使用

Field(&Foo::Bar::foobar, x) 

但是这种方式我必须检查我的结构中的每个字段,这似乎是大量的打字工作…

好吧,那我就对自己说:

必须为Foo::Bar:

提供操作符==实现
bool operator==(const Foo::Bar& first, const Foo::Bar& second)
{
    ...
}

不要将其作为成员函数添加到Foo::Bar中,而是使用自由函数。

并且,吸取的教训是,要注意不要将它们放到匿名命名空间中。