Search code examples
c++googletestgooglemock

How to mock a derived class that calls its base class methods?


I am unit testing a derived class and want to EXPECT_CALL that a certain method belonging to its base class is called.

For example:

class Base {
public:
    void move(int x, int y);
};

class Derived: public Base{
public:
    RESULT update();

private:
    int age;
};

HRESULT Derived::update(void) {
    int param1 = 5, param2 = 10;
    move(param1, param2);
    age++;

    return SUCCESS;
}

I can't just create a mock for Derived and expect move since there is no dependency and the actual move() will be called.

How can I be able to mock move()? My end goal is that I need to expect move() to be called with CORRECT parameter values (param1 and param2 in this case).

Of course this isn't the actual code but just a representation

I know this is not good design as far as UT is concerned, but this is to test some legacy code I am not allowed to reformat (but need to make UT). So being able to mock and test move() is the best option I have really.

Help will be appreciated. Thanks!


Solution

  • I don't think there is any way without using some preprocessing tricks. And of those tricks making method virtual when testing should be least painfull. It is enough to do something like:

    #if UNDER_TEST
    #define TEST_VIRTUAL virtual
    #else
    #define TEST_VIRTUAL
    #endif
    
    class Base {
    public:
        TEST_VIRTUAL void move(int x, int y);
    };
    

    Then you can mock it like this:

    class TestObject : public Derived {
    public:
        MOCK_METHOD2(move, void(int x, int y));
    };
    
    TEST(Test, Testing)
    {
        TestObject obj;
        EXPECT_CALL(obj, move(5, 10));
        obj.update();
    }