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

杀马特。学长 韩版系。学妹 提交于 2019-12-06 00:44:50

问题


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


回答1:


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




回答2:


Class MockB inherits from IB which has two purely abstract functions: test1 and test2. And you need to override both of them. Inheriting from MockA which overrides test1 is insufficient (at lest in C++ - in Java it would work). So the fix is to add

virtual int test1(int a)
{
    return MockA::test1(a);
}

to MockB definition.



来源:https://stackoverflow.com/questions/5484906/can-a-mock-class-inherit-from-another-mock-class-in-googlemock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!