C++ Google Mock - EXPECT_CALL() - expectation not working when not called directly

5.1k views Asked by At

I'm still pretty new to Google Mock so learning as I go. I've just been adding some unit tests and I've run into an issue where I can't get ON_CALL() to correctly stub a method called from within a method.

The following code outlines what I have;

class simpleClass
{
    public:
        bool simpleFn1()  { return simpleFn2(); }
        virtual bool simpleFn2()  { return FALSE; }
}

In my unit test I have:

class simpleClassMocked : public simpleClass
{
    private:
        MOCK_METHOD0(simpleFn2, bool());
}

class simpleClassTests : public ::testing::Test
{
}

TEST_F(simpleClassTests, testSimpleFn2)
{
    shared_ptr<simpleClassMocked> pSimpleClass = shared_ptr< simpleClassMocked >(new simpleClassMocked());

    ON_CALL(*pSimpleClass, simpleF2()).WillByDefault(Return(TRUE));

    // This works as expected - simpleFn2() gets stubbed
    pSimpleClass->simpleFn2();

    // This doesn't work as expected - when simpleFn1 calls simpleFn2 it's not the stubbed expectation???
    pSimpleClass->simpleFn1();
}

I figure I must be missing something obvious here, can anyone help? Thanks!

1

There are 1 answers

1
Daksh Gupta On BEST ANSWER

you'll have to Mark the method as virtual and add a corresponding MOCK function in the simpleClassMocked class

class simpleClass
{
    public:
        virtual bool simpleFn1()  { return simpleFn2(); }
        virtual bool simpleFn2()  { return FALSE; }
}

Also, you need to put the Mock methods in the public area

class simpleClassMocked : public simpleClass
{
    public:
        MOCK_METHOD0(simpleFn2, bool());
        MOCK_METHOD0(simpleFn1, bool());
}

It will work now