Search code examples
c++testinggooglemock

Is there OutOfSequence?


In Google Mock, is there any inverse of InSequence? E.g. OutOfSequence

E.g. the assertion only works if the correct sequence does NOT occur.


Solution

  • AFAIK, there is not a feature like that which you can use directly, however, it's not hard to get to what you want.

    Say you want the test fail if the following sequence of calls happen:

    Disconnect() -> Connect()
    

    You ask EXPECT_CALL to register the call sequences in a vector and then you can check to see if the sequence vector is what you expected. You can do this using Invoke, by using WillOnce and a lambda function that gets invoked when the function is called.

    Here is an example that checks if Disconnect() -> Connect() sequence does not happen.

    using ::testing::ElementsAre;
    using ::testing::Not;
    
    // Test if two functions are called out of sequence.
    TEST(AtmMachine, OutOfSequence) {
      std::vector<std::string> sequenceVector;
    
      // Arrange
      MockBankServer mock_bankserver;
    
      // Assuming we want the test fail if Disconnect happens before Connect.
      // We store their sequence in sequenceVector.
      EXPECT_CALL(mock_bankserver, Disconnect())
          .Times(1)
          .WillOnce(
              [&sequenceVector]() { sequenceVector.push_back("Disconnect"); });
    
      EXPECT_CALL(mock_bankserver, Connect())
          .Times(1)
          .WillOnce([&sequenceVector]() { sequenceVector.push_back("Connect"); });
    
      // Act
      AtmMachine atm_machine(&mock_bankserver);
      atm_machine.Withdraw(1234, 1000);
    
      // Assert that the Disconnect() -> Connect() does not happen
      EXPECT_THAT(sequenceVector, Not(ElementsAre("Disconnect", "Connect")));
    }