Search code examples
c++unit-testinggoogletestgooglemockotl

When passing gmock object as reference the setup expectations doesnt match


I want to test the behaviors of the following class.

class DAO{
    otl_connect *conn;
    public:
        DAO(otl_connect* _conn){
            conn = _conn;
        }

        bool init(){
            bool ret = true;
            try{
                conn->rlogon("ABC");
            }catch(otl_exception &e){
                ret = false;
            }
            return ret;
        }
};

To do that I created a derived mock class from otl_connect;

class MockOtlConnect : public otl_connect {
    public:
        MOCK_METHOD0(logoff, void());
        MOCK_METHOD1(rlogon, void(const char *connect_str));
};

In my test it is created an expectation to the function call rlogon

TEST(TesteMockOtlConnect, MockingOtlConnect){
    MockOtlConnect mock;
    EXPECT_CALL(mock, rlogon("ABC"));

    DAO dao(&mock);
    EXPECT_TRUE(dao.init();
}

But this expectation never get satisfied.

Actual function call count doesn't match EXPECT_CALL(mock, rlogon("ABC"))...
         Expected: to be called once
           Actual: never called - unsatisfied and active

Solution

  • Problem is wrong matcher. By writing:

    EXPECT_CALL(mock, rlogon("ABC"));
    

    You are not expecting call of rlogon with a string "ABC", but you are expecting call with some pointer value which you do not have control over it. Reason is that your argument type of is const char *

    To fix it use StrEq() matcher.

    EXPECT_CALL(mock, rlogon(StrEq("ABC")));