Search code examples
c++unit-testingtemplatesmockinggooglemock

How to mock a template class with gmock (Google Mock)?


I have a class template as following:

struct DailyQuote_t;
struct TickQuote_t;

template <typename Q>
class QtBuffer_t {
public:
   virtual int size() const noexcept = 0;
};

When testing another class named OrderBook_t, the instances QtBuffer_t<DailyQuote_t> and QtBuffer_t<TickQuote_t> are both required.

class OrderBook_t {
public:
   void setDependent( const QtBuffer_t<DailyQuote_t>* pDB, const QtBuffer_t<TickQuote_t>* pTB ) noexcept {
      m_pDBuf = pDB;
      m_pTBuf = pTB;
   };

   bool update() {
      m_pDBuf->size();
      m_pTBuf->size();
   };

private:
   const QtBuffer_t<DailyQuote_t>* m_pDBuf;
   const QtBuffer_t<TickQuote_t>*  m_pTBuf;
};

I tried to mock the template as following, but I failed:

template<typename Q>
class QtBufferMock : public QtBuffer_t<Q> {
public:
   MOCK_METHOD( int, size, (), ( const, noexcept, override ) );
};

Finally I have to mock them respectively:

class DailyBufferMock : public QtBuffer_t<DailyQuote_t> {
public:
   MOCK_METHOD( int, size, (), ( const, noexcept, override ) );
};

class TickBufferMock : public QtBuffer_t<TickQuote_t> {
public:
   MOCK_METHOD( int, size, (), ( const, noexcept, override ) );
};

Is there a way we can mock a class template with single mock?


Solution

  • Well by looking at the cook_book https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md you can in fact do it. It might be interesting maybe to check if you are using the latest version.