skip to content

GoogleMock Expectations

MOCK_METHOD declares a mock, EXPECT_CALL sets an expectation with matchers and cardinality, and ON_CALL sets a default. Interviewers ask about strict, nice and naggy mocks.

on this pageshow

explore

questions

6

In GoogleMock, how do you declare a mock method with MOCK_METHOD and set an expectation on it with EXPECT_CALL?

level: middleimportance: must knowfreq 70%

answer

  1. return type, name, parenthesised args
  2. qualifiers in a fourth group
  3. expectations before the calls
  4. verified when the mock dies

basics

~20 s

MOCK_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 s

A 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
cpp
#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 test

go deeper

for a junior

Recall the four-part MOCK_METHOD shape and that EXPECT_CALL names the mock object and the method with its argument matchers.

for a middle

Explain the clause order, the inferred cardinality rules, and why a test reports a missing call only when the mock is destroyed.

for a senior

Show you can read a GoogleMock failure: which expectations were tried, which argument mismatched, and whether the count was exceeded or unmet.

for a principal

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
open as a page

In GoogleMock, what is the difference between ON_CALL and EXPECT_CALL, and when should a test use each?

level: middleimportance: must knowfreq 65%

basics

~20 s

ON_CALL sets a mock method's default behaviour and verifies nothing. EXPECT_CALL adds a constraint: the call must happen, with matching arguments, the stated number of times. Stub with ON_CALL; use EXPECT_CALL only for calls the test verifies.

open as a page

When two GoogleMock EXPECT_CALLs on one method both match a call, which one wins, and how do InSequence and RetiresOnSaturation change that?

level: seniorimportance: should knowfreq 45%

basics

~20 s

GoogleMock searches expectations in reverse declaration order and uses the newest active one that matches, even if it is saturated. RetiresOnSaturation lets a full expectation step aside; InSequence makes expectations match only in the order declared.

open as a page

A GoogleMock test warns "Uninteresting mock function call" for one method and fails with "Unexpected mock function call" for another. What separates the two, and how do NiceMock, NaggyMock and StrictMock change each?

level: seniorimportance: should knowfreq 55%

basics

~20 s

An uninteresting call hits a method with no EXPECT_CALL; an unexpected call hits a method that has EXPECT_CALLs, none of which match. Unexpected calls always fail. NiceMock silences uninteresting calls, NaggyMock (the default) warns, StrictMock fails them.

open as a page

As a lead, what GoogleMock policy would you set for a codebase on nice versus strict mocks, ON_CALL versus EXPECT_CALL, and which types tests may mock?

level: principalimportance: should knowfreq 35%

basics

~20 s

Default to NiceMock or naggy mocks and keep StrictMock for protocols where any extra call is a bug; stub with ON_CALL and use EXPECT_CALL only for the interaction under test; mock only interfaces the team owns, through adaptors, with one shared mock per interface.

open as a page

In GoogleMock, how do you mock a dependency whose member functions are not virtual, and what must change in the code under test?

level: seniorimportance: nice to knowfreq 35%

basics

~20 s

Write a mock class unrelated to the real one, with MOCK_METHOD members of the same signatures and no override, and make the code under test a template on the dependency type. Production instantiates it with the real class, tests with the mock.

open as a page