kzaiwo
kzaiwo

Reputation: 1768

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!

Upvotes: 2

Views: 1398

Answers (2)

sklott
sklott

Reputation: 2859

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

Upvotes: 4

Marek R
Marek R

Reputation: 38092

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?

Upvotes: 2

Related Questions