问题
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