Search code examples
c++googletestgooglemock

In Google Test Framework, how to expect a function call OR another function call?


How is it possible to put in logical OR two EXPECT_CALL macros? Due to external factor, my test could result in a call to on_found() or to a function called on_not_found(). For my test scope is the same, because the important thing is that the search has been made. But I do not have access to the internal search() function and expect a call to that.


Solution

  • You can add some boolean variables to the test and make them true when on_found() or on_not_found() is called, and check logical OR of the variables at the end of the test. For example,

    auto onFoundCalled = false;
    auto onNotFoundCalled = false;
    EXPECT_CALL(mockObj, on_found())
        .Times(AtMost(1)).WillRepeatedly(InvokeWithoutArgs([&onFoundCalled]
    {
        onFoundCalled = true;
    }));
    EXPECT_CALL(mockObj, on_not_found())
        .Times(AtMost(1)).WillRepeatedly(InvokeWithoutArgs([&onNotFoundCalled]
    {
        onNotFoundCalled = true;
    }));
    
    RunSomeCode();
    
    ASSERT_TRUE(onFoundCalled || onNotFoundCalled);