Combining two mocks in one class (multiple mock inheritance)? #4661
Replies: 1 comment
-
Combining Multiple Mocks into One in C++ with Google MockIn Google Mock, it’s common to write one mock per interface, and the situation you described — where a class implements two interfaces and you want to mock both interfaces in one object — is a known challenge. When using A good approach to combine two mocks into one is to create a utility class that wraps both mocks and properly forwards method calls to the respective mocks. You can achieve this without the need to inherit from both mocks or repeat the Solution: Use a Template ClassYou can create a Here's an example of how this could look: template <typename Mock1, typename Mock2>
class CombinedMock : public Mock1, public Mock2 {
public:
// Constructor: Initializes both mocks
CombinedMock() : Mock1(), Mock2() {}
// Example of forwarding the call to the first mock
using Mock1::someMethodFromMock1;
// Example of forwarding the call to the second mock
using Mock2::someMethodFromMock2;
};
---
Explanation:
CombinedMock<Mock1, Mock2> inherits from both Mock1 and Mock2. This allows you to mock both interfaces in one object.
By using using statements, you can forward specific methods to each mock. This eliminates the need to manually repeat MOCK_METHOD for each method from the two interfaces.
This approach keeps the code clean and reusable, avoiding the need to write a mock specifically for the combination or manually repeating the MOCK_METHOD lines. |
Beta Was this translation helpful? Give feedback.
-
We like to write one mock per interface and recently discovered that when a class implements two interfaces and we want to have a single mock for that class, we cannot do it by inheriting from the mocks of both interfaces. For example NiceMock only has an effect on one of the two interfaces when we do this.
Is there an easy way to combine two mocks into one without the problems you get from inheriting from two mocks and without writing a mock specifically for the combination and repeating all the MOCK_METHOD lines?
It seems like it would be a useful utility to have a template class CombinedMock<Mock1, Mock2> that could do this with one line of code.
Beta Was this translation helpful? Give feedback.
All reactions