Question

Is there a neater and/or briefer way to set multiple identical actions than repeated use of WillOnce? Is there a way for WillRepeatedly to have a cardinality, for example?

I can only find examples that chain WillOnce potentially followed by a single WillRepeatedly, which is less than ideal for situations where I may want to return a value the first N times a function is called and then return a different value the last time, e.g. using a mock to represent obj in the following example and have it loop N times:

while (obj.IsDone())
{
    SomeAction(obj.NextItem());
}
Was it helpful?

Solution

You can use Times.

// This is the final call
EXPECT_CALL(obj, IsDone())
  .WillOnce(Return(true));
// These are the intermediate calls
EXPECT_CALL(obj, IsDone())
  .Times(N)
  .WillRepeatedly(Return(false))
  .RetiresOnSaturation();

The mock object's IsDone method will return false the first N times it's called. After that, the most recent expectation will have been satisfied, so we instruct it to no longer apply by using RetiresOnSaturation. Subsequent calls to IsDone will be handled by the first expectation, causing it to return true. If it's called any more times, the test will fail.

If you omit RetiresOnSaturation, then the second expectation will continue to apply; it will continue returning false, and you'll get messages alerting you that the "over-saturated and active" expectation is failing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top