Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock calling to base class with gmock

Given 2 classes like below:

class Base
{
public:
    virtual void doSmt(void);
}

class Derived : public Base
{
    void doSmt(void) { Base::doSmt(); }
}

Class I need to test is Derived. But I don't want to go deeper in Base, I just want to check that a call to Base is called inside doSmt()

Something like this:

TEST_F(Derived, DoSmt)
{
    EXPECT_CALL(Base, doSmt()).Times(1);
    testedInstance.doSmt();
}

Because I already have test for Base, and Base was inherited by 2 classes.

Is there any way?

like image 690
LongLT Avatar asked Nov 16 '25 09:11

LongLT


1 Answers

I was assigned to write unittest for "evil" design beside with gmock. From the beginning it's harder than I though, but I also have my own solution for this.

It simple than I though (again :D)

1.Insert into Base class header any mock needed. Or you can create a new one and specify its path include.

class Base
{
public:
    MOCK_METHOD0(mock_doSmt, void());
    void doSmt(void);
}

2.For calling to Base mock method, just create BaseStub.cpp

This source purpose for mocking only. So that, you have to compile & link with BaseStub.cpp instead of Base.cpp

void Base::doSmt(void) { mock_doSmt(); }

3.When test

EXPECT_CALL(*reinterpret_cast<Base*>(&derivedInstance), mock_doSmt()).Times(1);

mock_doSmt instead of doSmt

This way can resolve Singleton too. Create SingletonStub like above, and in SetUp() just singletonInstance = Singleton::getInstance();

Remember: This way, you have 2 source and 2 header.

When facing this fool, I recognized that should use #include <...> instead of #include "..."

Cause to when you specify include dir, #include <...> will let you more control.

And another important I'd like to share is

Do not abstract so much your OOP. Cause It will take you (or your colleague) into a very big troubles after that. Don't inherit more than 2 level, just 1 interface and 1 inherit.

like image 94
LongLT Avatar answered Nov 18 '25 00:11

LongLT