Search code examples
googletestgooglemock

How to mock a local variable initialized with the member variable


I have two classes Class A and Class SRD (Sample classes for understanding the problem. Real classes are different). Both classes have same Function(method1) with same arguments. Both are not derived from different Classes.

Class SRD is the member of Class A. a function in Class A creates a new object for SRD and calls method1(). It should call the mock function. but it calls the actual implementation

I have Written mock classes for both the classes and defined the mock method in both the classes and Wrote EXPECT_CALL in TEST function

    class A{
        private:
            SRD* srd;

        public :
         bool  Method1();
         bool MethodX();
         SRD* getsrd() {return srd;}
    };

    bool A :: MethodX()
    {

        srd.Method1(); // Not Calling Mock Method - Calling Actual 
     //Implementation
    }

    bool A::Method1()
    {
        ....
    }

    class SRD{

    public:
       bool Method1();
    };

    class MockSRD : public SRD{
        MOCK_METHOD0(Method1, bool())
    };

    class MockA : public MockA{
        MOCK_METHOD0(Method1, bool())
    };


    bool SRD::Method1()
    {
        ....
    }

    class TestA : public A {};

    TEST_F(TestA, test1)
    {
        MockSRD srd;

        EXPECT_CALL(srd, Method1())
        .Times(testing::AnyNumber())
        .WillRepeatedly(Return(true));

        srd.Method1() //Working fine - Caling mock Method;
        MethodX()
    }

When i call s1.Method1(), It should call the mock method. how should i do that ?

I don't want to change the production code.


Solution

  • Thanks for taking time to respond the Question . @Chris Oslen & @sklott

    I forgot to make the base class method to Virtual. Its worked fine when i change the base class methods