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

故事扮演 提交于 2021-01-28 03:05:25

问题


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!


回答1:


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();
}



回答2:


In this code there is noting to mock. You do not have here any external dependency.

Test for this code can look like this:

TEST(DerivedTest, WhenUpdateIsCalledPossitionIsChangedAndItGetsOlder)
{
    Derived foo;
    foo.age = 1;
    foo.update();
    EXPECT_EQ(10, foo.x);
    EXPECT_EQ(12, foo.y);
    EXPECT_EQ(2, foo.age);
}

Show me the reason there is sense to mock here anything?



来源:https://stackoverflow.com/questions/56750603/how-to-mock-a-derived-class-that-calls-its-base-class-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!