简体   繁体   中英

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 ?

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++

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM