开发者

Google Mock: multiple expectations on same function with different parameters

开发者 https://www.devze.com 2023-02-28 01:26 出处:网络
Consider the case where a certain mocked function is expected to be called several times, each time with a different value in a certain parameter. I would like to validate that the function was indeed

Consider the case where a certain mocked function is expected to be called several times, each time with a different value in a certain parameter. I would like to validate that the function was indeed called once and only once per value in a certain list of values (e.g. 1,2,5).

On the other hand, I would like to refrain from defining a sequence as that would dictate a certain order, which is an implementation detail I would l开发者_开发技巧ike to keep free.

Is there some kind of matcher, or other solution for this case?

I'm not sure if this influences the solution in any way but I do intend to use WillOnce(Return(x)) with a different x per value in the list above.


By default gMock expectations can be satisfied in any order (precisely for the reason you mention -- so you don't over specify your tests).

In your case, you just want something like:

EXPECT_CALL(foo, DoThis(1));
EXPECT_CALL(foo, DoThis(2));
EXPECT_CALL(foo, DoThis(5));

And something like:

foo.DoThis(5);
foo.DoThis(1);
foo.DoThis(2);

Would satisfy those expectations.

(Aside: If you did want to constrain the order, you should use InSequence: https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#expecting-ordered-calls-orderedcalls)


If you expect a function, DoThing, to be called with many different parameters, you can use the following pattern:

for (auto const param : {1, 2, 3, 7, -1, 2}){
    EXPECT_CALL(foo, DoThing(param));
}

This is particularly helpful if your EXPECT_CALL includes many parameters, of which only one is changing, or if your EXPECT_CALL includes many Actions to be repeated.

0

精彩评论

暂无评论...
验证码 换一张
取 消