Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a mock class inherit from another mock class in googlemock?

Can a mock class inherit from another mock class in googlemock? If yes, then please help me in understanding why isn't this working.

class IA
{
public:
   virtual int test1(int a) = 0;
};

class IB : public IA
{
public:
   virtual float test2(float b) = 0;
};

class MockA : public IA
{
public:
   MOCK_METHOD1(test1, int (int a));
};

class MockB : public MockA, public IB
{
public:
   MOCK_METHOD1(test2, float (float b));
};

I get a cannot instantiate abstract class compiler error for MockB but not for MockA

like image 488
Rishabh Avatar asked Mar 30 '11 10:03

Rishabh


People also ask

Does gMock come with gtest?

gMock is bundled with googletest.

What is gtest mock?

Google Test is a popular C++ unit testing framework developed by Google that can be used together with the closely related mocking extension framework, Google Mock, to test code that conforms to the SOLID principles for object-oriented software design.

How do you mock a function in C++?

It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class). public: ... virtual bool Open(const char* path, const char* mode) { return OpenFile(path, mode); } };


1 Answers

If you plan on using multiple inheritance, you should be using virtual inheritance.

Next example compiles and link fine :

class IA
{
    public:
        virtual int test1(int a) = 0;
};

class IB : virtual public IA
{
    public:
        virtual float test2(float b) = 0;
};

class MockA :virtual public IA
{
    public:
        int test1(int a)
        {
            return a+1;
        }
};

class MockB : public MockA, public IB
{
    public:
        float test2(float b)
        {
            return b+0.1;
        }
};

int main()
{
    MockB b;
    (void)b;
}

It is just a small modification of your example

like image 128
BЈовић Avatar answered Sep 29 '22 08:09

BЈовић