How to mock templated methods using Google Mock?

Xavier V. picture Xavier V. · Aug 6, 2010 · Viewed 18.8k times · Source

I am trying to mock a templated method.

Here is the class containing the method to mock :

class myClass
{
public:
    virtual ~myClass() {}

    template<typename T>
    void myMethod(T param);
}

How can I mock the method myMethod using Google Mock?

Answer

Ismael picture Ismael · Aug 6, 2010

In previous version of Google Mock you can only mock virtual functions, see the documentation in the project's page.

More recent versions allowed to mock non-virtual methods, using what they call hi-perf dependency injection.

As user @congusbongus states in the comment below this answer:

Google Mock relies on adding member variables to support method mocking, and since you can't create template member variables, it's impossible to mock template functions

A workaround, by Michael Harrington in the googlegroups link from the comments, is to make specialized the template methods that will call a normal function that can be mocked. It doesn't solve the general case but it will work for testing.

struct Foo
{
    MOCK_METHOD1(GetValueString, void(std::string& value));

    template <typename ValueType>
    void GetValue(ValueType& value); 

    template <>
    void GetValue(std::string& value) {
        GetValueString(value);
    } 
};