skip to content

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

level: middleimportance: must knowfreq 65%

answer

  1. behaviour versus constraint
  2. WillByDefault is the only action
  3. EXPECT_CALL actions win
  4. verify only what the test is about

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.

solid answer

~40 s

`ON_CALL(mock, Method(matchers)).WillByDefault(action)` answers "what happens if this is called?" and sets no expectation, so the test passes whether the method runs zero or fifty times. `EXPECT_CALL` answers "must this be called?": it fails the test on a missing, extra or mismatched call, and its `WillOnce`/`WillRepeatedly` actions take precedence over the `ON_CALL` default. An `EXPECT_CALL` without actions runs the default action, so the two combine well: `ON_CALL` for the canned sensor reading, `EXPECT_CALL` for the heater command under test. GoogleMock's cookbook calls `ON_CALL` the most under-used construct and recommends it by default, because every extra `EXPECT_CALL` over-specifies the implementation. A call to a method with no `EXPECT_CALL` is still uninteresting and draws a warning on a plain mock, even when an `ON_CALL` supplied its behaviour.

code

cpp · 27 lines
cpp
#include <gmock/gmock.h>
#include <gtest/gtest.h>

class Sensor {
 public:
  virtual ~Sensor() = default;
  virtual double ReadCelsius() const = 0;
};
class MockSensor : public Sensor {
 public:
  MOCK_METHOD(double, ReadCelsius, (), (const, override));
};

using ::testing::Return;

TEST(Thermostat, ExpectCallWithoutActionUsesOnCallDefault) {
  MockSensor sensor;
  ON_CALL(sensor, ReadCelsius()).WillByDefault(Return(25.0));  // behaviour only
  EXPECT_CALL(sensor, ReadCelsius());   // constraint: exactly one call
  EXPECT_EQ(sensor.ReadCelsius(), 25.0);  // no WillOnce, so the ON_CALL action runs
}

TEST(Thermostat, OnCallAloneVerifiesNothing) {
  MockSensor sensor;
  ON_CALL(sensor, ReadCelsius()).WillByDefault(Return(25.0));
  // ReadCelsius() is never called and the test still passes.
}

go deeper

for a junior

Remember that ON_CALL means default behaviour and EXPECT_CALL means a call the test requires.

for a middle

Walk through how an action is chosen: EXPECT_CALL actions, then the newest matching ON_CALL, then the built-in default value.

for a senior

Show how over-specified EXPECT_CALLs make refactors break tests, and lay out a fixture that stubs with ON_CALL and verifies one interaction per test.

for a principal

Treat the ON_CALL-first style as a maintenance-cost decision for a whole codebase and decide how reviews enforce it.

## Two macros, two jobs A mocked method in GoogleMock can be configured in two ways, and the difference is whether the test makes a claim about the call: | | `ON_CALL` | `EXPECT_CALL` | |---|---|---| | Sets behaviour (what the call returns or does) | yes, via `WillByDefault` | yes, via `WillOnce` / `WillRepeatedly` | | Sets an expectation that can fail the test | no | yes | | Required clause | `.WillByDefault(action)`, exactly once | none | | Optional clauses | `.With(...)` | `.With`, `.Times`, `.InSequence`, `.After`, `.WillOnce`, `.WillRepeatedly`, `.RetiresOnSaturation` | | Silences the uninteresting-call warning | no | yes, for that method | Both take the same matcher syntax, `Method(matchers...)`, and both apply only to calls whose arguments match. ## How the actions combine When a mocked method is called, GoogleMock decides what to do in this order: 1. If a matching `EXPECT_CALL` has a `WillOnce` left, or a `WillRepeatedly`, that action runs. 2. Otherwise the **default action** runs: the newest matching `ON_CALL`'s `WillByDefault`. 3. If no `ON_CALL` matches either, GoogleMock returns a default value: `false` for `bool`, `0` for other built-in types and pointers, a default-constructed object for a default-constructible type, or a value registered with `DefaultValue<T>::Set()`. So an `EXPECT_CALL(sensor, ReadCelsius())` with no action, next to `ON_CALL(sensor, ReadCelsius()).WillByDefault(Return(25.0))`, returns 25.0 and still demands exactly one call. The first test in the example shows exactly that. ## Why the cookbook recommends `ON_CALL` by default It is tempting to think `EXPECT_CALL` is simply the stronger, safer choice. GoogleMock's cookbook argues the opposite: **a good test verifies the contract of the code**, and every `EXPECT_CALL` adds a constraint. If the thermostat reads the sensor twice per tick today and once tomorrow after an optimisation, a test that wrote `EXPECT_CALL(sensor, ReadCelsius()).Times(2)` breaks although nothing observable changed. A common layout follows from that: - the fixture's `SetUp` installs `ON_CALL` defaults shared by every test: a plausible temperature, a passing self-test; - each `TEST_F` adds one or two `EXPECT_CALL`s for the single behaviour it verifies, such as the heater command; - tests that need a different reading override it with a newer `ON_CALL`, or with `WillOnce` on an `EXPECT_CALL` when the call itself is part of the claim. In code, that layout looks like this: ```cpp class ThermostatTest : public ::testing::Test { protected: void SetUp() override { ON_CALL(sensor_, ReadCelsius()).WillByDefault(Return(21.0)); ON_CALL(sensor_, SelfTest()).WillByDefault(Return(true)); } NiceMock<MockSensor> sensor_; MockActuator heater_; }; TEST_F(ThermostatTest, ColdRoomTurnsHeaterOn) { ON_CALL(sensor_, ReadCelsius()).WillByDefault(Return(16.0)); // newer wins EXPECT_CALL(heater_, SetHeater(true)); // the one claim Tick(sensor_, heater_, 20.0); } ``` The newer `ON_CALL` in the test body takes precedence over the fixture's, because `ON_CALL`s, like expectations, are searched from the most recently declared backwards; the two lists have separate precedence orders and do not interact. The only `EXPECT_CALL` is the behaviour the test name promises, so a change to how often the sensor is read leaves the test green. ## The warning `ON_CALL` does not silence A method that has no `EXPECT_CALL` at all is **uninteresting** when it is called. On a plain mock, GoogleMock prints `Uninteresting mock function call` and takes the default action, and that happens whether the default came from an `ON_CALL` or from the built-in value; the warning then reads "taking default action specified at" the `ON_CALL` line. The test does not fail. There are three honest responses to it: - wrap the mock in `NiceMock<>`, which suppresses uninteresting-call warnings for that object; - add `EXPECT_CALL(mock, Method(_)).Times(AnyNumber())` for that one method, which allows any calls without enforcing them; - accept the warning while developing, since it can reveal a call the author forgot about. What the warning's own note warns against is adding a bare `EXPECT_CALL(mock, Method())` just to make the message go away: that silently turns a harmless call into a requirement of exactly one call. ## Interview checklist - `ON_CALL` never fails a test by itself; a test with only `ON_CALL`s verifies nothing about interactions. - `EXPECT_CALL` actions override `ON_CALL` defaults; an action-less `EXPECT_CALL` falls back to them. - Prefer `ON_CALL` for stubbing and `EXPECT_CALL` for the interaction under test. - Silence noise with `NiceMock` or `Times(AnyNumber())`, never with an unintended exact expectation.

  • Two ON_CALLs match the same call in GoogleMock. Which one supplies the default action?
    The newer one. GoogleMock searches `ON_CALL` specifications, like expectations, from the most recently defined backwards and uses the first that matches. That lets a fixture install a broad default in `SetUp()` and a test body override it with a narrower `ON_CALL` declared later.
  • How do you make a mocked method return a value computed from its arguments rather than a constant?
    Pass a callable as the action: `ON_CALL(m, Scale(_)).WillByDefault([](int x) { return 2 * x; });` or use `Invoke` with a function, or delegate to a hand-written fake with the cookbook's DelegateToFake pattern. The action receives the call's arguments, so it can compute the result instead of returning a fixed value.

  • Calling EXPECT_CALL always better because it verifies more
  • Expecting an ON_CALL to fail the test when the method is never called
  • Adding a bare EXPECT_CALL just to silence the uninteresting-call warning
  • Thinking an EXPECT_CALL without an action returns zero even when an ON_CALL matches
  • Believing ON_CALL suppresses the uninteresting-call warning on a plain mock