Search code examples
googletestgooglemock

EXPECT_CALL not able to track the calls for methods called from the method under test


First of all, I'm new to Google test, so please forgive my ignorance, if any. I'm writing unit tests using google test framework for the below class..

class MsgHandler
{
    public:
        MsgHandler(){}
        ~MsgHandler(){}
        bool decode_data(unsigned char*, unsigned int,char *);
        bool handle_req_state_data(char *, char *);
};

bool MsgHandler::handle_req_state_data(char *a, char *b)
{
    printf("handle_req_state_data called\n");
    return true;
}

bool MsgHandler::decode_data(unsigned char *a, unsigned int b,char *c)
{
    printf("decode_data called\n");
    handle_req_state_data(c, c);
    return true;
}

As a first step, I have created the mock class as below

class MsgHandlerMock : public MsgHandler
{
    public:
        MsgHandlerMock()
        {
        }

        virtual ~MsgHandlerMock() {}

        MOCK_METHOD(bool, handle_req_state_data, (char *, char *), (const));
        //MOCK_METHOD(int, decode_data, (unsigned char*, unsigned int ,char* ));
    private:
};

Below is the test function

TEST_F(TestClass, test01)
{
    MsgHandlerMock mockObj;

    //EXPECT_CALL(mockObj, decode_data(::testing::_,::testing::_,::testing::_)).Times(1);
    EXPECT_CALL(mockObj, handle_req_state_data(::testing::_,::testing::_)).Times(1);

    mockObj.decode_data(0,0,0);
}

My intention of this test is to make sure 'handle_req_state_data' is called when I call 'decode_data' with a certain message. But my test fails with below error

decode_data called
handle_req_state_data called
...
Actual function call count doesn't match EXPECT_CALL(mockObj, handle_req_state_data(::testing::_,::testing::_))...
         Expected: to be called once
           Actual: never called - unsatisfied and active
[  FAILED  ] TestClass.test01 (1 ms)
[----------] 1 test from TestClass (1 ms total)

Can someone help me on how to validate the inner method calls with EXPECT_CALL validators?


Solution

  • The function is not virtual, so can't be overridden by the mock, decode_data does not use dynamic dispatch and call the original method MsgHandler::handle_req_state_data.

    virtual bool handle_req_state_data(char *, char *);
    
    MOCK_METHOD(bool, handle_req_state_data, (char *, char *), (override));