Search code examples
c++tddgooglemock

Avoid matching .WillOnce multiple times in Google Mock


I have a mock object setup that looks like this:

MyObject obj;
EXPECT_CALL(obj, myFunction(_))
.WillOnce(Return(1))
.WillOnce(Return(1))
.WillOnce(Return(1))
.WillRepeatedly(Return(-1));

Is there a way to not have to repeat .WillOnce(Return(1)) three times?


Solution

  • You can use .Times(nn) followed by .WillRepeatedly(... to solve this:

    using testing::InSequence;
    
    MyObject obj;
    
    {
      InSequence s;
      EXPECT_CALL(obj, myFunction(_))
          .Times(3)
          .WillRepeatedly(Return(1));
      EXPECT_CALL(obj, myFunction(_))
          .WillRepeatedly(Return(-1));
    }