C++ – When to mark a function as virtual

cmockingunit testingvirtual-functions

I'm trying to understand the idiomatic way to code. I'm using gmock to unit test the components I write. Gmock requires methods to be virtual to be able to mock but the class I'm trying to mock has a non virtual method that I would like to be mocked out.

So the options are to either mark the methods as virtual or create an interface with pure virtual methods. Neither of them seems ideal as I would be doing either of them just to test the code. How is it usually approached in the C++ world?

Best Answer

Your design or test is wrong.

Instead of mocking using a framework, try create your own derived class and design your test around this "mock" class. You will realize that idea of mocking non-virtual methods doesn't make any sense. The idea of virtual methods is that the base class wants some functionality and expects it's children to provide it. If the base class does not make method virtual, it means it doesn't expect it's children to change the behavior of that method. And as such it is integral part of the class and should be tested as such. Mocking out non-virtual method would mean you aren't testing whole behavior of the base class.

One thing that comes to mind, that would "force" you to do this is that the base class has multiple responsibilities and that it should be separated into multiple classes where the non-virtual one is actually API of the extracted class.