Search code examples
c++unit-testingoverridinggoogletestgooglemock

I modified gtest/gmock so it is really easy to mock non-virtual functions



You know sometimes when something does not work and you want a quick fix you get stupid ideas ... I mean really stupid ideas. But somehow they work. So to be able to mock non-virtual functions I deleted every "override" in the google test framework and now my program runs smoothly.
(Not a single bug. It works as expected.)

So my question is. How risky is this method and am I stupid ?

I came to that conclusion to do it because the only two reasons to write override is:

  • Make the code more readable
  • Compiler checks if it is actually a method to override (protects you)

I am using c++


Solution

  • I hate to be the bearer of bad news, but by deleting those overrides you disabled the safeties to shoot yourself in the proverbial foot.

    Non-virtal functions do not get added to the V-table. This means that if you do the following:

    class Foo
    {
      public:
        int doThings() { return 42; };
    }
    
    class MockFoo : public Foo
    {
      public:
        int doThings() { return -1; };
    }
    

    You will not have virtual function calls, i.e. if you call doThings() on a Foo* you will always call Foo::doThings() and get 42, no matter if the underlying object is a Foo or a MockFoo. Or in other words:

    class Bar
    {
      public:
        int doBarThings(Foo* foo) { return foo->doThings() + 10; };
    }
    
    TEST_F(BarTest, doThings)
    {
        Bar bar;
        MockFoo mockFoo;
        bar->doBarThings(&mockFoo);
    }
    

    Will always result in Foo::doThings() being called (even though you provide a MockFoo), because Bar::doBarThings(Foo* foo) expects a Foo pointer, and the function doThings() in Foo is non-virtual.