Using Google Mock with boost::bind

Using Google Mock with boost::bind

本文关键字:bind boost with Google Mock Using      更新时间:2023-10-16

我有一个类,它的构造函数接受一个Boost函数,我想用Google Mock测试它。下面的代码显示了一个样例类和我对它的测试:

MyClass.h:

#include <boost/function.hpp>
class MyClass
{
public:
    MyClass(boost::function<void()> callback);
    void callCallback();
private:
    boost::function<void()> m_callback;
};

MyClassTest.cpp:

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <boost/bind.hpp>
#include "MyClass.h"
class CallbackMock
{
public:
    MOCK_METHOD0(callback, void());
};
TEST(MyClassShould, CallItsCallback)
{
    CallbackMock callbackMock;
    MyClass myClass(boost::bind(&CallbackMock::callback, callbackMock));
    EXPECT_CALL(callbackMock, callback()).Times(1);
    myClass.callCallback();
}

尝试在Visual Studio 2008中编译MyClassTest.cpp会出现以下错误:

…gmock/gmock-generated-function-mockers.h (76):错误C2248:内部测试::::FunctionMockerBase:: FunctionMockerBase":不能访问私有成员在课堂上声明"内部测试::::FunctionMockerBase"1>与1> [1>
F=void (void) 1>>
/gmock-spec-builders.h(1656):见宣言内部测试::::FunctionMockerBase:: FunctionMockerBase"1>与1> [1>
F=void (void) 1>>
此诊断发生在编译器生成函数内部测试::::FunctionMocker:: FunctionMocker (const内部测试::::FunctionMocker&)' 1> with [1>
Function=void (void) 1>]

错误源于包含boost::bind的行。用void callback(){}替换Mock方法消除了编译错误(但也消除了Google Mock的使用,违背了目的)。在不修改测试类的情况下,我要做的是什么?

原因是Google Mock模拟是不可复制的——这是设计上的。当您尝试按值将其传递给boost::bind时,编译器无法生成复制构造函数。您应该在将mock的地址传递给bind时使用它:

MyClass myClass(boost::bind(&CallbackMock::callback, &callbackMock));

我认为这行是错误的:

MyClass myClass(boost::bind(&CallbackMock::callback, callbackMock));

最后一个参数应该是&callbackMock