Google Mock: ON_CALL
+ EXPECT_CALL
A short post about how ON_CALL
and EXPECT_CALL
can complement each other. It is worth remembering that EXPECT_CALL
does not “override” behaviors defined by ON_CALL
. Both of these macros can be used simultaneously on the same mock.
ON_CALL - defines the default action for a mocked function, e.g.
ON_CALL(myMock, myMethod(1)).WillByDefault(Return(11));
ON_CALL
s can override each other. The one that was defined last will be matched. For example:
ON_CALL(myMock, myMethod(_)).WillByDefault(Return(999));
ON_CALL(myMock, myMethod(1)).WillByDefault(Return(111));
myMock.myMethod(1); // 111
myMock.myMethod(2); // 999
ON_CALL(myMock, myMethod(_)).WillByDefault(Return(123));
myMock.MyMethod(1); // 123
Above, the placeholder _
was used, which matches any argument. It is also possible to use only the function name to define the default action for all its calls:
ON_CALL(myMock, myMethod).WillByDefault(Return(999));
This notation will work provided that the function name myMethod
is not overloaded.
EXPECT_CALL - defines an assertion that must be met for the test to pass, e.g.
EXPECT_CALL(myMock, myMethod(4)).WillRepeatedly(Return(44));
Above, an assertion was defined that the myMethod
function must be called with the argument 4
and if it happens, return 44
.
Combining ON_CALL
and EXPECT_CALL
Both of these macros can complement each other.
ON_CALL(myMock, myMethod(_)).WillByDefault(Return(999));
ON_CALL(myMock, myMethod(1)).WillByDefault(Return(111));
EXPECT_CALL(myMock, myMethod(1));
EXPECT_CALL(myMock, myMethod(2));
myMock.myMethod(1); // 111
myMock.myMethod(2); // 999
In this way, you can separate assertions from actions taken by mocks. It doesn’t always make sense, but it’s worth remembering that you can do it.