1

I am trying to create a proxy class with virtual system call wrappers so that in the functional code, I can define these wrappers to make system calls, but in unit test, making them mock methods. This is my current idea but it feels clumsy. Is there any better way to achieve this?

SysCallAgent.hpp

#include <string>
#include <memory>

class SysCallAgent
{
public:
SysCallAgent(){}
virtual ~SysCallAgent(){}

    static SysCallAgent& instance()
    {
        if(!_pInstance)
        {
            _pInstance = std::move(std::make_unique<SysCallAgent>());
        }
        return *_pInstance.get();
    }
    
    //reset is for setting instance as mock object in unit test
    static void reset(std::unique_ptr<SysCallAgent>&& pInstance)
    {
        _pInstance = std::move(pInstance);
    }
    
    
    virtual void system_call1();
    virtual void system_call2();
    ...
    

private:
    static std::unique_ptr<SysCallAgent> _pInstance;
};

=========================the functional code project========================

SysCallAgent.cpp

void SysCallAgent::system_call1()
{
   /// make the actual system call
}

void SysCallAgent::system_call1()
...

==========================unit test project============================

test.cpp

class MockSysCallAgent : public SysCallAgent
{
    MOCK_METHOD0(system_call1, void());
    MOCK_METHOD1(system_call2, void());
    ....
}

TEST(test, test)
{
    SysCallAgent::reset(std::move(std::unique_ptr<MockSysCallAgent>()));
}
...
Quarra
  • 2,527
  • 1
  • 19
  • 27
Pracka
  • 159
  • 1
  • 8

1 Answers1

1

The idea is OK IMHO, and the code is fine too I guess with one caveat: you're injecting MockSysCallAgent as unique_ptr so you don't have an access to this object anymore. In GoogleMock, you have to set the expectations on the very same object that is used in the code under test, i.e. the expect calls are the internal state of the mock object and are not copied etc. To inject unique_ptr like this you can use technique posted in this question.

Quarra
  • 2,527
  • 1
  • 19
  • 27