Google Mock: Override EXPECT_CALL

EXPECT_CALL is not overridable. This does not mean that you cannot have multiple EXPECT_CALLs for the same function.

EXAMPLE 1

EXPECT_CALL(myMock, myMethod(1));
EXPECT_CALL(myMock, myMethod(2));

In the test, both EXPECT_CALLs will be in effect. The test will pass only if the myMethod function is called once with the argument 1 and once with the argument 2. The order of these calls does not matter.

The test will fail if:

EXAMPLE 2

EXPECT_CALL(myMock, myMethod(_));
EXPECT_CALL(myMock, myMethod(1));

In the test, both EXPECT_CALLs must be fulfilled exactly once. However, you have to be careful because EXPECT_CALLs are matched in reverse order of appearance in the code. That is:

Therefore two calls to the myMethod(1) function will cause an error because the second EXPECT_CALL will be matched and fulfilled twice. The test will pass only if the myMethod function is called twice, once with the argument 1 and once with an argument other than 1. The order of these calls does not matter.

EXAMPLE 3

EXPECT_CALL(myMock, myMethod(1));
EXPECT_CALL(myMock, myMethod(_));

In the test, both EXPECT_CALLs will be in effect, but the first one will never be fulfilled because myMethod(_) will always be checked first, which matches everything.

In particular, the test will fail when:

EXAMPLE 4

EXPECT_CALL(myMock, myMethod(1));
EXPECT_CALL(myMock, myMethod(_)).RetireOnSaturation();

In the test, both EXPECT_CALLs will be in effect. First, an attempt will be made to match the second one (we always check from the end), and if it is fulfilled, it will stop being in effect. From this moment, only the first EXPECT_CALL for the myMethod(1) function will be active.

The test will pass when:

The test will fail when:

EXAMPLE 5

EXPECT_CALL(myMock, myMethod(_));
EXPECT_CALL(myMock, myMethod(1)).RetireOnSaturation();

In the test, both EXPECT_CALLs will be in effect. First, an attempt will be made to match the second one (we always check from the end), and if it is fulfilled, it will stop being in effect.

The test will pass when:

The test will fail when:

Note that if you remove .RetireOnSaturation(), the test will stop passing for the case of calling myMethod twice with the argument 1, because both calls will match the second, always active, EXPECT_CALL, causing a fail.

EXAMPLE 6

EXPECT_CALL(myMock, myMethod(1));
EXPECT_CALL(myMock, myMethod(1));

The above test will never pass because each call to myMethod(1) will always be matched to the second EXPECT_CALL.

EXPECT_CALL(myMock, myMethod(1));
EXPECT_CALL(myMock, myMethod(1)).RetireOnSaturation();

Now the test will pass when the myMethod function is called twice with the argument 1. The second EXPECT_CALL will be active only for the first call. The above test is equivalent to using Times(2):

EXPECT_CALL(myMock, myMethod(1)).Times(2);

See also