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

我正在尝试为包含三个重载方法的类编写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,
卢卡斯

解决方法

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

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

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

最后,你需要从Foo继承FooMock.

所以把它们放在一起,你得到的结果如下:

#include <memory>
#include <string>
#include "gtest/gtest.h"
#include "gmock/gmock.h"

using ::testing::_;
using ::testing::An;
using ::testing::Matcher;
using ::testing::TypedEq;
using ::testing::Return;

struct Foo {
  virtual ~Foo() {}
  virtual int fooMethod(const int&) { return 0; }
  virtual int fooMethod(const float&) { return 0; }
  virtual int fooMethod(const std::string&) { return 0; }
};

struct FooMock : Foo {
  FooMock() : Foo() {
    ON_CALL(*this,fooMethod(An<const int&>())).
        WillByDefault(Return(-1));
    ON_CALL(*this,fooMethod(Matcher<const float&>(_))).
        WillByDefault(Return(-2));
    ON_CALL(*this,fooMethod(TypedEq<const std::string&>("1"))).
        WillByDefault(Return(-3));
  }

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

TEST(Foo,foo) {
  std::shared_ptr<Foo> foo(new FooMock);
  auto foo_mock(std::dynamic_pointer_cast<FooMock>(foo));

  EXPECT_CALL(*foo_mock,fooMethod(Matcher<const int&>(_))).Times(1);
  EXPECT_CALL(*foo_mock,fooMethod(Matcher<const float&>(_))).Times(1);
  EXPECT_CALL(*foo_mock,fooMethod(Matcher<const std::string&>(_))).Times(1);

  EXPECT_EQ(-1,foo->fooMethod(1));
  EXPECT_EQ(-2,foo->fooMethod(1.0f));
  EXPECT_EQ(-3,foo->fooMethod("1"));
}


int main(int argc,char **argv) {
  testing::InitGoogleTest(&argc,argv);
  return RUN_ALL_TESTS();
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...