MOCK_METHOD 名称必须后跟 '::' 必须是 class 或命名空间名称

MOCK_METHOD name must be followed by '::' must be a class or namespace name

给定一个接口 class Foo:

#ifndef FOO_H
#define FOO_H
#include <string>
class Foo
{
    public:
        Foo() = default;
        virtual ~Foo() = default;
        virtual void bar(std::string msg) = 0;
};
#endif

它的模拟:

#ifndef FOO_MOCK_H
#define FOO_MOCK_H
#include "gtest/gtest.h"
#include "gmock/gmock.h"
class MockFoo: public Foo
{
    public:
        MOCK_METHOD(void, bar, (std::string), (override));
};
#endif

还有一个愚蠢的测试:

#include "pch.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "MockFoo.h"

using ::testing::NiceMock;

TEST(SillyTests, Silly)
{
    std::string msg = "Hello, world!";
    NiceMock<MockFoo> mock_foo;
    EXPECT_CALL(mock_foo, bar)
        .Times(1);
    mock_foo.bar(msg);
}

在 gtest 和 gmock 内部的一大堆错误中,Visual Studio 抱怨 MOCK_METHOD() 和 "name followed by '::' must be a class or namespace name",并且找不到 MOCK_METHOD 的函数定义。

有趣的是,添加旧函数调用 MOCK_METHODn 会产生相同的错误。

MOCK_METHOD1(debug, void(std::string msg));

将鼠标悬停在 MOCK_METHOD 上会显示几个静态断言,但它们似乎并不正确。它们包括:

gmock 版本为 1.10.0,Google测试适配器版本为 1.8.1.3。

解决了。 googlemock 和 googletest 不共享同一版本是原因。将 googlemock 降级到 v1.8.1 解决了这个问题。

This method does not take "1" arguments. Parenthesize all types with unprotected commas

虽然您看到的可能有所不同,但我遇到了这个问题并将我带到这里,所以添加了我对相关问题的回答。上面引用的错误可能是因为宏是如何处理的,这就是它所要求的:

// To mock following
virtual void func(int a, std::map<int, int> m) = 0

// This won't work since argument list enclosed parses by splitting
// using ',' and sees 3 arguments, int a, std::map<int and int> m.
MOCK_METHOD(void, func, (int a, std::map<int, int> m), (override));

// However properly paranthesizing it make it see just 2 arguments as expected and works:
MOCK_METHOD(void, func, (int a, (std::map<int, int> m)), (override));