1

I've starting using HippoMocks for writing unit tests. I would like to know if it's possible to mock non-virtual class methods?

A first look at the code seems to indicate that the framework only supports virtual methods. But as it supports the mocking of simple C functions, it should be possible to do the same for non-virtual class methods.

Is there a way to achieve that?

Serge Weinstock
  • 1,235
  • 3
  • 12
  • 20
  • A straightforward method is to add a specifier `TEST_VIRTUAL` in front of all non-virtual methods of the class under test and define it to `virtual` when building in the unit test context. But that is only fine if you don't mind modifying the code under test only for the sake of testability which is arguably not the cleanest unit testing method. I would use this only as a last resort. – Roland Sarrazin Sep 22 '16 at 13:45

1 Answers1

1

It's not impossible, but it would lead to very weird use mechanisms - or no possibility for thread-safety.

C functions are flat-out always mocked. In that case it's always redirecting to the mock, you cannot call the original anymore.

C++ virtual functions are only mocked for the requested object, and any other object will still have the regular function there.

C++ non-virtual functions would look like a virtual function, but only be mockable on a per-class level. It's also very likely that your compiler will inline these functions, making it not likely to be reliable.

I've had a patch from somebody that just applied it blindly, and it suffered from the described problems. You'd need to be 100% sure that any access to that member function is not inlined, which is just about impossible.

dascandy
  • 7,184
  • 1
  • 29
  • 50