Google Mock: multiple expectations from the same function with different parameters

Consider the case when it is expected that some mocked function will be called several times, each time with a different value in a certain parameter. I would like to confirm that the function was actually called once and only once per value in a specific list of values ​​(e.g. 1,2,5).

On the other hand, I would like to refrain from determining the sequence, since this will dictate a certain order, which is a detail of the implementation that I would like to keep for free.

Is there any socket or other solution for this case?

I'm not sure if this has any effect on the solution, but I intend to use WillOnce (Return (x)) with a different x value for the value in the list above.

+8
source share
2 answers

By default, gMock expectations can be met in any order (precisely for the reason you mentioned - so you don’t overdo 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 these expectations.

(Beyond: if you want to limit the order, use InSequence : https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#expecting-ordered-calls-orderedcalls )

+11
source

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

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

This is especially useful if your EXPECT_CALL includes many parameters, of which only one changes, or if your EXPECT_CALL includes many EXPECT_CALL that need to be repeated.

+1
source

Source: https://habr.com/ru/post/886384/


All Articles