Search code examples
googletestgooglemock

How to set an EXPECT_CALL to function being called after a specific time?


I'm setting some expectations (using gtest and gmock) on some functions, like:

EXPECT_CALL(mockedTimer, expired()).Times(1);

How can I set a expectation to do something like:

"Expect that this function will be executed exactly in 100ms" ?


Solution

  • Probably the easiest way to do this would be to set up a timer which measures how long it takes for expired() to be invoked, and add a test assertion that the duration is 100ms.

    In the context of a test, it would look something like this:

    void startStopwatch();
    void stopStopwarch();
    unsigned getStopwatchResult();
    
    TEST(TimerTest, TimerExpiresIn100ms) {
    
        // set up mockTimer, etc.
        EXPECT_CALL(mockedTimer, expired()).WillOnce(Invoke(&stopStopwatch));
        startStopwatch();
        // test logic, which waits until expired() is called, goes here
        ASSERT_EQ(100u, getStopwatchResult());
    }
    

    This is very rough, of course, but you get the idea.

    Let me know if this is helpful. On an editorial note, in general, tests that rely on specific timing (i.e. they rely on an event occuring within a specific time frame) are rather unreliable. Unless there's a very good reason for this 100ms constraint, it might be worthwhile to re-think the test logic :)