Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock method implementation using Google Mock

I'm mocking Arduino millis method using Google Mock. This method returns number of milliseconds since device starts. I would like to return increased number (in range 0 to Infinity) on every method call.

So far, I'm mocking this function like that:

EXPECT_CALL(*arduino, millis())
  .WillOnce(Return(0))
  .WillOnce(Return(1))
  .WillOnce(Return(2))
  // and so on...

But it's impractical. Is there a better way which works on infinite number of calls?

like image 918
user1518183 Avatar asked Nov 19 '15 18:11

user1518183


People also ask

How does Google mock work?

Using Google Mock involves three basic steps: Use some simple macros to describe the interface you want to mock, and they will expand to the implementation of your mock class; Create some mock objects and specify its expectations and behavior using an intuitive syntax; Exercise code that uses the mock objects.

What is mock implementation?

mockImplementation(fn) ​ Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called.

What is gMock used for?

Google's C++ Mocking Framework or GMock for short, is an open sourced, free and extendible library for creating fake objects, use them, set behavior on them without the need to change the class with each and every test.


1 Answers

You can write a custom action that will return incrementing numbers and use it in WillRepeatedly:

ACTION(ReturnIncreasingIntegers) {
    static int n = 0;
    return ++n;
}

EXPECT_CALL(*arduino, millis())
    .WillRepeatedly(ReturnIncreasingIntegers());

But I would advise against that. The less deterministic your test is, the harder it is to understand the behavior of the code under test there.

like image 119
VladLosev Avatar answered Sep 22 '22 22:09

VladLosev