In GoogleMock, how do you declare a mock method with MOCK_METHOD and set an expectation on it with EXPECT_CALL?
answer
- return type, name, parenthesised args
- qualifiers in a fourth group
- expectations before the calls
- verified when the mock dies
basics
~20 sMOCK_METHOD(ReturnType, Name, (Args...), (Specs...)) in a public section generates the mock member. EXPECT_CALL(mock, Name(matchers...)) then states, before the code runs, which calls must happen, how often, and what they return; unmet expectations fail when the mock is destroyed.
solid answer
~40 sA mock class derives from the interface and declares each member with `MOCK_METHOD(return_type, name, (args...), (specs...))`, where the optional specs are `const`, `override`, `noexcept`, `ref(&)`/`ref(&&)` or `Calltype(...)`. The macro must sit in the `public:` section, and a type with an unprotected comma such as `std::pair<bool, int>` needs extra parentheses or an alias. In the test, `EXPECT_CALL(mock, Method(matchers...))` names the call; arguments are matched by values (`Eq` implied), `_`, or matchers like `Gt`, `HasSubstr` and `Field`. Chained clauses then set `.Times(...)`, `.WillOnce(Return(...))` and `.WillRepeatedly(...)`. Expectations must be set **before** the mock is exercised; GoogleMock reports a call to an expected method that matches none of its expectations, or exceeds one, at the moment it happens, and checks for unsatisfied expectations in the mock's destructor.
code
cpp · 30 lines#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>
struct Command { int percent; std::string reason; };
class Actuator {
public:
virtual ~Actuator() = default;
virtual void Apply(const Command& cmd) = 0;
};
class MockActuator : public Actuator {
public:
MOCK_METHOD(void, Apply, (const Command& cmd), (override));
};
void Regulate(double celsius, double target, Actuator& heater) {
if (celsius < target) heater.Apply({80, "too cold"});
}
using ::testing::AllOf; using ::testing::Field;
using ::testing::Gt; using ::testing::HasSubstr;
TEST(Thermostat, HeatsHardWhenCold) {
MockActuator heater;
EXPECT_CALL(heater, Apply(AllOf(Field(&Command::percent, Gt(50)),
Field(&Command::reason, HasSubstr("cold")))));
Regulate(16.0, 20.0, heater);
} // heater is destroyed here: an unmet expectation fails the testgo deeper
Recall the four-part MOCK_METHOD shape and that EXPECT_CALL names the mock object and the method with its argument matchers.
Explain the clause order, the inferred cardinality rules, and why a test reports a missing call only when the mock is destroyed.
Show you can read a GoogleMock failure: which expectations were tried, which argument mismatched, and whether the count was exceeded or unmet.
Weigh how much each EXPECT_CALL constrains the implementation; matchers that pin every field make refactoring expensive across a large suite.
## The two halves of a GoogleMock test GoogleMock, the mocking library shipped with GoogleTest, splits a mock-based test into two pieces of code: - a **mock class**, written once per interface, whose members are generated by the `MOCK_METHOD` macro; - **expectations**, written in each test with `EXPECT_CALL`, that say which calls the code under test must make, with which arguments, how many times, and what each call returns. In the thermostat example below, the controller drives an `Actuator` interface. The test replaces it with `MockActuator` and checks that a cold room produces a strong heating command. ## Declaring the mock with `MOCK_METHOD` The macro mirrors the method declaration in four arguments: ```cpp MOCK_METHOD(return_type, method_name, (args...), (specs...)); ``` - The argument list is always parenthesised, even when empty: `()`. - The optional fourth group holds qualifiers: `const` (required when overriding a `const` member), `override` (recommended for a virtual member), `noexcept` (required when the base member is `noexcept`), `ref(&)` or `ref(&&)` for ref-qualified members, and `Calltype(...)` for Windows calling conventions. - `MOCK_METHOD` must appear in the `public:` section of the mock, even when the base declares the member `protected` or `private`. - A **comma inside a type** breaks the macro's argument parsing: `MOCK_METHOD(std::pair<bool, int>, GetRange, ());` does not compile. Wrap the type in parentheses, `(std::pair<bool, int>)`, or give it an alias. The older `MOCK_METHOD0`, `MOCK_CONST_METHOD1` family still compiles, but the cookbook recommends migrating to `MOCK_METHOD`, which arrived in 2018. When no action is given, a mocked function returns a **default value**: `false` for `bool`, `0` for other built-in types and pointers, and a default-constructed object when the return type has a default constructor. ## Setting an expectation with `EXPECT_CALL` `EXPECT_CALL(mock_object, method(matchers...))` creates an expectation. Each matcher stands for one argument: | Written as | Matches | |---|---| | a plain value, or `Eq(v)` | an argument equal to `v` | | `_` | any value of the right type | | `Gt(v)`, `Le(v)`, `Ne(v)` | a comparison against `v` | | `HasSubstr("cold")` | a string containing the substring | | `Field(&Command::percent, m)` | an object whose member matches `m` | | `AllOf(m1, m2)`, `AnyOf(...)`, `Not(m)` | a combination of other matchers | Omitting the parentheses entirely, `EXPECT_CALL(mock, Method)`, acts as if every argument were `_`, but only for a method that is not overloaded. Clauses chain after the macro in a fixed order: `.With()`, `.Times()`, `.InSequence()`, `.After()`, any number of `.WillOnce()`, at most one `.WillRepeatedly()`, and `.RetiresOnSaturation()` last. ## How many calls: the inferred cardinality When `.Times()` is omitted, GoogleMock infers it from the actions: 1. no `WillOnce` and no `WillRepeatedly`: exactly one call, `Times(1)`; 2. *n* `WillOnce` clauses and no `WillRepeatedly`: exactly *n* calls; 3. *n* `WillOnce` clauses plus one `WillRepeatedly`: at least *n* calls, `Times(AtLeast(n))`. So `.WillOnce(Return(17.0)).WillOnce(Return(23.0))` expects exactly two calls, and a third call fails as "called more times than expected". Explicit cardinalities are `Exactly(n)` (or a bare `n`), `AtLeast(n)`, `AtMost(n)`, `Between(m, n)` and `AnyNumber()`. ## When the verdict arrives - A call that exceeds an expectation's upper bound, or matches none of the method's expectations, is reported **immediately**, with the arguments and every expectation that was tried. - An expectation that was never satisfied is reported when the **mock object is destroyed**, usually at the closing brace of the test. A leaked heap mock is never verified, which is why GoogleMock reports leaked mocks as failures by default. - Expectations must be set **before** the code under test calls the mock. The documentation calls interleaving `EXPECT_CALL` with calls to the mock **undefined behaviour**: read `EXPECT_CALL` as a promise about future calls. The example test passes when `Regulate` sends `{80, "too cold"}`. If it sent 40 percent, the call would fail immediately as unexpected, and the destructor would also report the expectation as never called. ## Mistakes interviewers listen for - **Expectations after the action.** Calling `Regulate(...)` first and writing `EXPECT_CALL` afterwards is not a late check; GoogleMock's documentation calls it undefined behaviour. - **Assuming `.WillOnce` means "at least once".** One `WillOnce` without `Times` infers exactly one call; a second call is an upper-bound failure. - **Matching whole objects.** `Apply(Eq(expected_command))` needs an `operator==` and breaks whenever any field changes; `Field(&Command::percent, Gt(50))` states only the property the test is about. - **Forgetting `const`.** Mocking a `const` member without the `const` spec declares a different, non-overriding function; with `override` in the specs the compiler catches it, which is why the reference recommends `override` on virtual members. - **Heap mocks that are never deleted.** Their expectations are never verified; prefer stack mocks or smart pointers that the test owns.
- Why does MOCK_METHOD(std::map<int, double>, Snapshot, ()); fail to compile, and how do you fix it?`MOCK_METHOD` is a preprocessor macro, and the preprocessor splits arguments on every top-level comma, including the one inside `std::map<int, double>`. Wrap the type in parentheses, `MOCK_METHOD((std::map<int, double>), Snapshot, ());`, or introduce an alias such as `using Readings = std::map<int, double>;` and use that. Argument types need the same treatment: `((std::map<int, double>), bool)`.
- What does a mocked method return when its expectation has no WillOnce or WillRepeatedly action?It performs the default action. If an `ON_CALL(...).WillByDefault(...)` matches, that action runs; otherwise GoogleMock returns a default value: nothing for `void`, `false` for `bool`, `0` for other built-in types and pointers, and a default-constructed object for a default-constructible type. `DefaultValue<T>::Set()` changes the value for a type.
- Writing EXPECT_CALL after the code under test has already called the mock
- Believing unmet expectations are checked when RUN_ALL_TESTS returns
- Thinking two WillOnce clauses allow any number of calls
- Putting MOCK_METHOD in a protected section to match the base class
- Assuming a template type with a comma works unwrapped inside MOCK_METHOD