Search code examples
unit-testinggoogletestassertiongooglemock

How to make sure matcher of EXPECT_CALL doesn't increment the counter of the assertion when argument doesn't match?


I am matching the result of a mocked listener based on the type of event it receives. The expectation I want to define is "you should receive such type of event once and assert the following once. Any other event doesn't matter to me".

This is the assertion I've written so far

EXPECT_CALL(listener, changed(Field(&Event::type, Event::Type::processed)).WillOnce(/*Blablabla*/);

Theoretically my listener should receive two calls. One Event::Type::processed and one Event::Type::done. I explicitly do not want to "assert" anything about this latter. It seems though, that the Matcher will successfully match the Event::Type::processed, trigger the WillOnce... but will tell me at the end of the test that my expectation Times(1) is saturated because, although it didn't match the second event (Event::Type::processed) it still increments the overall counter of this expectation...

It's super annoying I just cannot find my way around it.
Needless to say that VerifyAndClear won't help here as these two events happen in one call and I don't intend to decouple it, it'd me meaningless for my model.


Solution

  • {
      testing::InSequence s;
      EXPECT_CALL(listener, changed(Field(&Event::type, Event::Type::processed)).WillOnce(/*Blablabla*/);
      EXPECT_CALL(listener, changed(_)).Times(testing::AnyNumber());
    }
    

    should do the trick for you.