Here's another workaround that doesn't require you to make a special mock class. All you need to do is to mock each of the base classes, and apply it to an instance of the deriving class by casting the deriving class to a reference of each interface. You do need to apply the mock to an instance of the class. Here is an example:
class I1
{
public:
virtual int one() = 0;
};
class I2
{
public:
virtual int two() = 0;
};
class Both : public I1, public I2
{
public:
virtual int one()
{
return 0;
}
virtual int two()
{
return 0;
}
virtual int three()
{
return one() + two();
}
};
We have pure interfaces I1
and I2
with pure virtual methods one()
and two()
respectively, all implemented by Both
. As you might guess, Both
is deliberately designed to produce an incorrect answer to demonstrate the mock. Here is the mock inside a Google Test test:
TEST(both_mock, three)
{
Both both;
Mock<I1> mock1((I1&)both);
Mock<I2> mock2((I2&)both);
When(Method(mock1, one)).Return(1);
When(Method(mock2, two)).Return(2);
ASSERT_EQ(both.three(), 3);
}
And this works and passes. The advantage of this is that you don't need to create a special mock class, and you can use the actual class that inherits multiple classes. The disadvantages are...
- The deriving class (
both
in this case) must be instantiable (e.g., you can't do this with an abstract class or interface that inherits from other abstract classes or interfaces).
- If you further subclass the subclass of both interfaces (e.g.,
class More : public Both
), you still need one mock for each interface/base class, and you cannot mock any member declared by Both
, More
, or any further deriving class.