c++googletestgooglemock

Mocking functions with multiple template arguments


I am trying to mock std::make_shared

#include <memory>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>

template <typename T, typename... Args>
class MakeSharedMock {
 public:
  MOCK_METHOD(std::shared_ptr<T>, MakeShared, (Args... args), (const noexcept));
};

int main(){
    MakeSharedMock<std::string> mock_make_shared;
}

However getting error like this

error: static assertion failed: This method does not take 1 arguments.
Parenthesize all types with unproctected commas.   
MOCK_METHOD(std::shared_ptr<T>, MakeShared, (Args... args), (const
noexcept));

If I omit first typename T, it compiles

template <typename... Args>
class MakeSharedMock {
 public:
  MOCK_METHOD(std::shared_ptr<int>, MakeShared, (Args... args), (const noexcept));
};

I wonder whether its possible to mock functions with multiple template arguments.


Solution

  • GMock seems to not support variadic template, but you might use specialization as workaround:

    template <typename T, typename... Args>
    class MakeSharedMock;
    
    template <typename T>
    class MakeSharedMock<T>
    {
     public:
      MOCK_METHOD(std::shared_ptr<T>, MakeShared, (), (const noexcept));
    };
    
    template <typename T, typename T1>
    class MakeSharedMock<T, T1>
    {
     public:
      MOCK_METHOD(std::shared_ptr<T>, MakeShared, (T1), (const noexcept));
    };
    
    template <typename T, typename T1, typename T2>
    class MakeSharedMock<T, T1, T2>
    {
     public:
      MOCK_METHOD(std::shared_ptr<T>, MakeShared, (T1, T2), (const noexcept));
    };
    
    // ...
    

    Demo