Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Mock: Return() a list of values

Via Google Mock's Return() you can return what value will be returned once a mocked function is called. However, if a certain function is expected to be called many times, and each time you would like it to return a different predefined value.

For example:

EXPECT_CALL(mocked_object, aCertainFunction (_,_))
    .Times(200);

How do you make aCertainFunction each time return an incrementing integer?

like image 223
Jonathan Livni Avatar asked Feb 28 '11 16:02

Jonathan Livni


People also ask

Does Gtest include gMock?

gMock is bundled with googletest.

How do you mock a function in gMock?

Mocking Free Functions It is not possible to directly mock a free function (i.e. a C-style function or a static method). If you need to, you can rewrite your code to use an interface (abstract class).

What is Expect_call Gtest?

EXPECT_CALL not only defines the behavior, but also sets an expectation that the method will be called with the given arguments, for the given number of times (and in the given order when you specify the order too).

What is gMock in C++?

Googletest Mocking (gMock) Framework Google's framework for writing and using C++ mock classes. It can help you derive better designs of your system and write better tests.


1 Answers

Use sequences:

using ::testing::Sequence;

Sequence s1;
for (int i=1; i<=20; i++) {
    EXPECT_CALL(mocked_object, aCertainFunction (_,_))
        .InSequence(s1)
        .WillOnce(Return(i));
}
like image 88
Jonathan Livni Avatar answered Oct 07 '22 20:10

Jonathan Livni