Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

how to set custom ref-variable in gmock

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 XXXClient {
public:
    void QueryXXX(const Request&, Response&);
}; 

class XXXRunner {
public:
    void DoSomething(XXXClient&);
};

There is a Client Class XXXRunner::DoSomething using XXXClient::QueryXXX, and I Want to mock XXXClient to test XXXRunner::DoSomething.

The problem occurs that the second parameter of QueryXXX , that is 'Response', is not a return value, but a reference variable, which I fill some data into Response in XXXClient::QueryXXX. I want to set a custom data for the Response to verify different condition of XXXRunner::DoSomething.

The gmock framework can set expected returned value, but I cannot not find a way to set the "returned variable" ?

So How to do so?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...