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

anh*_*ppe 6 c++ googlemock

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

请考虑以下代码:

class Foo
{
public:
    struct Bar
    {
        int foobar;
    }

    void myMethod(const Bar& bar);
}
Run Code Online (Sandbox Code Playgroud)

现在我有一些测试代码,它看起来像这样:

Foo::Bar bar;
EXPECT_CALL(fooMock, myMethod(Eq(bar));
Run Code Online (Sandbox Code Playgroud)

所以我想确保在调用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)
Run Code Online (Sandbox Code Playgroud)

我尝试使用Eq(ByRef(bar))来定义operator ==和!=(至少==都是自由函数的成员),但我无法解决问题.唯一有用的是使用

Field(&Foo::Bar::foobar, x) 
Run Code Online (Sandbox Code Playgroud)

但这样我必须检查我的结构中的每个字段,这似乎是很多打字工作......

anh*_*ppe 6

好的,那我就回答一下:

您必须为Foo :: Bar提供operator ==实现:

bool operator==(const Foo::Bar& first, const Foo::Bar& second)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

并且,经验教训,小心不要将它们放入匿名命名空间.