How to compare special fields in google mock?

冷暖自知 提交于 2019-12-11 07:29:46

问题


I have got question connected with google test. I would like to ask if while inducing "EXPECT_CALL(*A, some_method(mes1));" in test case there is possiblity to compare fields included in mes1 class.

struct Mes
{
    int a;
};

//short section of test case:
Mes mes1 = Mes();
EXPECT_CALL(*A, some_method(mes1));

I would like to ask if in google mock is a possiblity to compare special fields included in Mes. Something like:

EXPECT_CALL(*A, some_method(mes1), compare(Mes.a));//in this case google mock would compare only field "a" from Mes.

回答1:


It depends on what you want to do with the result of the comparison. If you simply want to query the value of the field, you can simply define a function to do something with it:

// Note: The signature of someFunction needs to match some_method.
void someFunction(const Mes& mes)
{
    // Do something with mes.a
}

Then set up your expectation as follows:

EXPECT_CALL(*A, some_method(mes1)).WillOnce(Invoke(someFunction));

Note that if some_method returns a value, you may also have to provide a Return action.

Alternatively, if you want your test to fail if the field isn't some specific value, you need to write a custom matcher:

MATCHER_P(MesFieldEq, val, "")
{
    return (arg.a == val);
}

Then use it in your expectation as follows:

// Fails unless mes.a is equal to 42.
EXPECT_CALL(*A, some_method(MesFieldEq(42));


来源:https://stackoverflow.com/questions/28193990/how-to-compare-special-fields-in-google-mock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!