我有一个Singleton类,它有私有Ctor、Dtor和一个getInstance()方法。
class Single {
public:
virtual void* alloc(size_t size, uint line){}
Single* getInstance() {
if(!m_Instance)
m_Instance = __OSAL_NEW OSAL_Memory;
return m_Instance;
}
private:
Single();
~Single();
static Single* m_Instance;
};
#define Allocate(size_t size)
(Single::getInstance())->alloc(size, __LINE__)
我需要使用GMOCK模拟这个类。有什么办法可以嘲笑它吗?
您可以使用工厂模式来创建对象。
#include <iostream>
#include <functional>
struct A
{
virtual ~A(){}
virtual void foo() = 0;
};
struct Areal : A
{
virtual void foo(){
std::cout<<"real"<<std::endl;
}
};
struct Amock : A
{
virtual void foo(){
std::cout<<"mock"<<std::endl;
}
};
struct Single
{
typedef std::function< A*() > CreatorFn;
static A* getInstance(){
if ( ! instance() )
instance() = (create())();
return instance();
}
static void setCreator( CreatorFn newFn ){
create() = newFn;
}
private:
static CreatorFn& create(){
static CreatorFn f( [](){return new Areal;} );
return f;
}
static A*& instance(){
static A* p=nullptr;
return p;
}
};
bool useMock = true;
int main()
{
if ( useMock )
{
Single::CreatorFn mockFn( [](){ return new Amock; } );
Single::setCreator( mockFn );
}
Single::getInstance()->foo();
}
您只需要确保在访问实例之前设置了创建者。否则,将调用默认的创建者函数。