2011-04-07 100 views
5

我有一个构造函数需要Boost函数的类,我想用Google Mock来测试它。下面的代码显示了一个示例类和我试图测试一下:使用Google Mock和boost :: bind

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(); 
} 

试图编译MyClassTest.cpp在Visual Studio 2008给出以下错误:

...gmock/gmock-generated-function-mockers.h(76) : error C2248: 'testing::internal::FunctionMockerBase::FunctionMockerBase' : cannot access private member declared in class 'testing::internal::FunctionMockerBase' 1> with 1> [ 1>
F=void (void) 1> ] 1>
.../gmock-spec-builders.h(1656) : see declaration of 'testing::internal::FunctionMockerBase::FunctionMockerBase' 1> with 1> [ 1>
F=void (void) 1> ] 1>
This diagnostic occurred in the compiler generated function 'testing::internal::FunctionMocker::FunctionMocker(const testing::internal::FunctionMocker &)' 1> with 1> [ 1>
Function=void (void) 1> ]

该错误源自含有嘘声的行T ::绑定。用void callback(){}替换模拟方法消除了编译错误(但也消除了使用Google Mock,达到目的)。我正在尝试做什么而不修改被测试的类?

回答

5

我觉得这条线是错误的:

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

最后一个参数应该是&callbackMock

+0

谢谢,本,它修复了它。 – 2011-04-07 21:48:22

16

的原因是,谷歌模拟嘲笑是不可拷贝 - 这是由设计。当您尝试通过值将其传递到boost::bind时,编译器无法生成复制构造函数。你应该把模拟地址传递到bind

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

感谢您的补充说明。 – 2011-04-07 21:49:15

+2

这真的应该是被接受的答案。你为我节省了很多时间!谢谢弗拉德! – 2012-03-18 18:54:44