c++ - 如何使用签名 `object ()` 模拟函数

标签 c++ mocking googlemock

我想模拟一个带有声明A::B X(void)的方法。定义如下。

class A {
    class B;
    virtual B X() = 0;
};

class A::B {
  public:
    auto_ptr<int> something;
};

我的模拟类,遵循这个,是相当标准的。

class mA : public A
{
  public:
    MOCK_METHOD0(X, A::B());
};

然而,编译后,这给了我这个奇怪的错误,而且我无法找到它。这有什么问题吗?

In member function ‘virtual A::B mA::X()’:
...: error: no matching function for call to ‘A::B::B(A::B)’
...: note: candidates are: A::B::B()
...:                       A::B::B(A::B&)

更新我找到了一个失败的代码示例来演示这一点。

#include <gmock/gmock.h>
#include <memory>
using std::auto_ptr;

class thing {
  public:
    class result;
    virtual result accessor () = 0;
};

class thing::result {
    auto_ptr<int> x;   // If this just "int", error goes away.
};

namespace mock {
    class thing : ::thing {
      public:
        MOCK_METHOD0 ( accessor, result() );
    };
}

最佳答案

如果没有 A 和 B 的定义,很难分辨。听起来它试图从临时对象构造 B,但失败了,因为它无法将临时对象绑定(bind)到非常量引用。

例如,您的复制构造函数可能定义为:

class A {
 public:
  class B {
   public:
    // This should be const, without good reason to make it otherwise.
    B(B&); 
  };
};

修复后只是使其成为常量引用。

关于c++ - 如何使用签名 `object ()` 模拟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3702731/

相关文章:

c++ - 将多个实现提取到静态库中

c++ - C++ 和重载运算符的新手,不确定如何使用该函数

c++ - 在函数的局部对象上使用 EXPECT_CALL?

c++ - 在循环中添加预期的调用

c++ - 无法调用命名空间方法

c++ - 组装的 C++ 似乎包含多余的指令

c++ - 在 OpenCV 中使用掩模和 ROI 计算轮廓内点的图像像素值(例如平均值)

android - RuntimeException : Method putExtra in android. content.Intent 未被模拟

Node.js:如何测试我的 API,模拟由我的 API 调用的第三方 API

javascript - 如何在 Node.js 中模拟所需的文件?