2

i need to mock a class that has only non virtual methods. This class has a copy constructor. How to I write a mock method for that. I get a compiler error if I just use the

MOCK_METHOD1(classname, void(classname& source)); 

Thanks in advance.

273K
  • 29,503
  • 10
  • 41
  • 64
Gentoo
  • 347
  • 2
  • 8
  • 16
  • 1
    I know this is old, but here's some documentation on mocking non-virtual methods: https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#mocking-nonvirtual-methods – wulfgarpro Jan 15 '17 at 10:29

1 Answers1

6

You can't mock non-virtual functions with gmock. So the first alternative to consider is to make the functions virtual. If you are concerned with performance overhead of making the functions virtual make sure that this really is a problem (by measuring), cause generally it ain't.

An alternative solution if there is no possibility to make the functions virtual is to use templates. See this question for details on this technique and this question for pros and cons of using it.

Community
  • 1
  • 1
Tobias Furuholm
  • 4,727
  • 4
  • 30
  • 39
  • Alternatively use the preprocessor to conditionally make your functions virtual in testing builds and keep them untouched (non-virtual) in production builds. Best of both worlds. One thing to keep in mind though: it breaks with polymorphic value members due to slicing. – Regexident May 14 '13 at 21:32