Search code examples
c++unit-testinggoogletestgooglemock

sleep() call inside gmock's EXPECT_CALL


I'm trying to do some sleep inside .WillOnce before invoking FuncHelper. So I need something similar to the following:

EXPECT_CALL(*_mock, Func(_,_,_)).Times(1)
  .WillOnce(DoAll(InvokeWithoutArgs(sleep(TimeToSleep)), 
                  Invoke(_mock, &M_MyMock::FuncHelper)));

Is it possible to call sleep() with an arg inside .DoAll? C++98 is preferrable.

UPD:

The solution is based on @Smeeheey answer and uses C++98.

template <int N> void Sleep ()
{
  sleep(N);
}
...
EXPECT_CALL(*_mock, Func(_,_,_)).Times(1)
  .WillOnce(DoAll(InvokeWithoutArgs(Sleep<TimeToSleep>), 
                  Invoke(_mock, &M_MyMock::FuncHelper)));

Solution

  • Since you said C++98 is preferable rather than compulsory, first I'll give a nice neat C++11 answer:

    EXPECT_CALL(*_mock, Func(_,_,_)).Times(1)
      .WillOnce(DoAll(InvokeWithoutArgs([TimeToSleep](){sleep(TimeToSleep);}), 
                      Invoke(_mock, &M_MyMock::FuncHelper)));
    

    Otherwise (for C++98), define a wrapper function elsewhere in the code:

    void sleepForTime()
    {
        sleep(TimeToSleep);
    }
    

    And then:

    EXPECT_CALL(*_mock, Func(_,_,_)).Times(1)
      .WillOnce(DoAll(InvokeWithoutArgs(sleepForTime), 
                      Invoke(_mock, &M_MyMock::FuncHelper)));
    

    Note that here, TimeToSleep will have to be a global variable.

    EDIT: As per suggestion from OP in comments, if TimeToSleep is a compile-time constant you can avoid the global variable:

    template <int Duration>
    void sleepForTime()
    {
        sleep(Duration);
    }
    
    ...
    
    EXPECT_CALL(*_mock, Func(_,_,_)).Times(1)
      .WillOnce(DoAll(InvokeWithoutArgs(sleepForTime<TimeToSleep>), 
                      Invoke(_mock, &M_MyMock::FuncHelper)));