Question

I wrote the following piece of code to test Xyz::xyz_func by mocking Abc::abc_func using Google Mock.

#include <iostream>
#include "gmock/gmock.h"
#include "gtest/gtest.h"

using namespace std;
using ::testing::_;
using ::testing::Return;

class Abc
{
    public:
        virtual ~Abc() {}

        virtual bool abc_func(int arg)  = 0;
};

class MockAbc : public Abc
{
    public:
        virtual ~MockAbc() { }

        MOCK_METHOD1(abc_func,  bool(int arg));
};

class AbcImpl : public Abc
{
    public:
        virtual bool abc_func(int arg)
        {
            cout << arg << " :: " << __FILE__ << " :: " << __LINE__ << endl;
            return true;
        }
};

class Xyz : public AbcImpl
{
    public:
        virtual ~Xyz() {}
        virtual bool xyz_func()
        {
            AbcImpl obj;
            return obj.abc_func(1);
        }
};

TEST(AbcTest, func_success)
{
    MockAbc *mock = new MockAbc();

    EXPECT_CALL(*mock,  abc_func(_)).WillOnce(Return(true));

    Xyz test;

    EXPECT_TRUE(test.xyz_func());

    delete mock;
}

int main(int argc, char** argv)
{
    ::testing::InitGoogleMock(&argc, argv);
    return RUN_ALL_TESTS();
}

But i get the below error. I want to know how we can tell Xyz class to call mock of abc_func instead of actual implementation. Could you please help me.

1 :: ./gmock_test.cpp :: 30
./gmock_test.cpp:50: Failure
Actual function call count doesn't match EXPECT_CALL(*mock, abc_func(_))...
         Expected: to be called once
           Actual: never called - unsatisfied and active
Was it helpful?

Solution

You are creating a mock object of type MockAbc but you never use it. From your code it appears that you're expecting the MockAbc instance you create to automagically replace the AbcImpl object that you explicitly create in Xyz::xyz_func.

What you need to be doing instead is using dependency inversion to allow the object used by xyz_func to be specified at runtime.

You don't need Xyz to inherit from AbcImpl or Abc.


Two potential solutions:

class Xyz {
public:
    explicit Xyz(Abc& obj) : 
        obj(&) {
    }

    virtual bool xyz_func() {
        return obj->abc_func(1);
    }
private:
    Abc* obj;
};

or

class Xyz {
public:
    virtual bool xyz_func(Abc& obj) {
        return obj->abc_func(1);
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top