使用GMOCK模拟具有私有构造函数的类

时间:2013-07-10 07:46:17

标签: c++ mocking singleton gmock private-constructor

我有一个带有私有Ctor,Dtor和一个getInstance()方法的Singleton类。

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模拟这个类。 有没有办法嘲笑它。

1 个答案:

答案 0 :(得分:0)

您可以使用factory pattern创建对象。

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

您只需确保在访问实例之前设置创建者。否则,将调用默认的创建者函数。