how to set custom ref-variable in gmock

前端 未结 2 867
心在旅途
心在旅途 2020-12-16 19:10

I am using gmock in my project and I meet a problem to set a custom reference variable for a mock function. Suppose I have a class as following:

class XXXCli         


        
相关标签:
2条回答
  • 2020-12-16 19:27

    First, make a XXXClient mock class, let's name it XXXClientMock as following:

    class XXXClientMock : public XXXClient
    {
    public:
        MOCK_METHOD2(QueryXXX, QueryResult (Request&, Response&));
    };
    

    Then, use GMock Action SetArgReferee to set the custom parameter, as following:

    TEST(XXXRunnerTC, SetArgRefereeDemo)
    {
        XXXCLientMock oMock;
    
        // set the custom response object
        Response oRsp;
        oRsp.attr1 = “…”;
        oRsp.attr2 = “any thing you like”;
    
        // associate the oRsp with mock object QueryXXX function
        EXPECT_CALL(oMock,  QueryXXX(_, _)).
            WillOnce(SetArgReferee<1>(oRsp));
        // OK all done
    
        // call QueryXXX
        XXXRunner oRunner;
        QueryResult oRst = oRunner.DoSomething(oMock);
        …
    
        // use assertions to verity your expectation
        EXPECT_EQ(“abcdefg”, oRst.attr1);
        ……
    }
    

    Summary
    GMock provide a series of actions to make it convenient to mock functions, such as SetArgReferee for reference or value, SetArgPointee for pointer, Return for return, Invoke for invoke custom mock function (with simple test logic), you can see here for more details.

    Enjoy it :) Thank you

    0 讨论(0)
  • 2020-12-16 19:40

    Check out the SetArgReferee in the Google Mock cheat sheet.

    0 讨论(0)
提交回复
热议问题