GMock - 使用ON_CALL为重载方法返回默认值

时间:2013-05-10 10:11:41

标签: c++ gmock

我正在尝试为包含三个重载方法的类编写mock,即:

#include <gtest/gtest.h>
#include <gmock/gmock.h>

using ::testing::_;
using ::testing::Return;
using ::testing::A;
using ::testing::ByRef;
using ::testing::Ref;
using ::testing::TypedEq;

struct Foo {
  int fooMethod(const int& intParam) { return 0; }
  int fooMethod(const float& floatParam) { return 0; }
  int fooMethod(const std::string& stringParam) { return 0; }
};

struct FooMock {
  FooMock() {
    ON_CALL(*this, fooMethod(_)).WillByDefault(Return(-1));
  }

  MOCK_METHOD1(fooMethod, int(const int& intParam));
  MOCK_METHOD1(fooMethod, int(const float& floatParam));
  MOCK_METHOD1(fooMethod, int(const std::string& stringParam));
};

但这会出错:

 error: call of overloaded ‘gmock_fooMethod(const testing::internal::AnythingMatcher&)’ is ambiguous

我也尝试过TypedEq()而不是“_”,但它会给出更多模糊的错误。我已经检查了GMock常见问题解答,Wiki和我没有找到解决方案 - 如何为重载方法返回ON_CALL的默认值?

BR, 卢卡斯

2 个答案:

答案 0 :(得分:10)

@ tx34是答案的关键,但代码中还有一些问题。

首先,Selecting Between Overloaded Functions上的文档是最合适的。您有三个fooMethod重载,其参数数量相同但参数类型不同。您将不得不使用指定类型的匹配器。

接下来,您需要定义所有要模拟为Foo的{​​{1}}函数,否则通过virtual对象调用它们将不会调用派生的模拟函数。由于您将Foo定义为基类,因此它还应该有一个虚拟析构函数来避免切片。

最后,您需要Foo继承FooMock

所以把它们放在一起,你最终得到的结果是:

Foo

答案 1 :(得分:2)

问题是TypedEq期望值不是匹配器。你可以通过以下方式实现目标:

ON_CALL(*this, fooMethod(An<ArgType>())).WillByDefault(Return(-1));

ON_CALL(*this, fooMethod(Matcher<ArgType>(_))).WillByDefault(Return(-1));

另见:

https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#selecting-between-overloaded-functions

https://github.com/google/googletest/blob/master/googlemock/docs/CheatSheet.md#wildcard

https://github.com/google/googletest/blob/master/googlemock/docs/CheatSheet.md#generic-comparison