Search code examples
unit-testinggoogletestgooglemock

Gmock - Check that a method is not called with a particular argument


There is a method with one string parameter virtual void method(const std::string& str) = 0;

In some cases, I need to be sure that this method is not called with a specific argument, for example, "321".

If the method is called somewhere as ifce->method("123"); and in tests I do EXPECT_CALL(mock, method("321")).Times(0); then the test fails:

Expected arg #0: is equal to "321"
       Actual: "123"
     Expected: to be never called
       Actual: never called - saturated and active
[  FAILED  ] test.invokeMethodWithDiferentParameters (0 ms)

How to do it correctly?


Solution

  • Either use testing::NiceMock, which ignores all uninteresting calls

    NiceMock<MockFoo> mock;
    EXPECT_CALL(mock, method("321")).Times(0);
    

    Or add several expectations

    EXPECT_CALL(mock, method(_)).Times(AtLeast(1));
    EXPECT_CALL(mock, method("321")).Times(0);