Using Google Mock with boost::bind
Using Google Mock with boost::bind
我有一个类,它的构造函数接受一个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
- boost::bind()类似的东西,但用于函数调用
- 泛化传递给 boost::bind 的参数
- Boost.Asio:不能使用 std::bind() 来指定回调
- boost::bind函数缓冲区的最大大小
- 自 1.55 以来,boost::bind / boost::function 中的奇怪行为变化
- 使用 boost::bind 进行订阅回调时出错
- 将 std::bind 应用于带有参数 <boost::asio::ip::tcp::socket> 时出错?
- 如何使用 boost::bind 附加参数?
- boost::bind 无法绑定到纯虚拟基类中定义的非静态函数模板成员类型
- 如何正确绑定成员函数与 boost::bind
- 将 boost::function 和 boost::bind 替换为模板
- Boost Asio - boost::bind 导致程序崩溃
- ioService.post(boost::bind(&myFunction, this, attr1, attri2) 不会发布作品
- 我可以使用 boost::bind 来存储不相关的对象吗?
- 在spirit parser Action中,在上下文参数上编译boost :: bind(成员函数)上的错误
- 如何使用 boost::bind 将返回 int 的函数转换为返回布尔值的函数
- boost::bind with member functions(作为boost::asio异步写入处理程序)
- 创建一个 boost::线程 带有 boost::bind() 或不带
- boost::bind & boost::function with partial args
- boost::bind, boost::shared_ptr and inheritance