skip to content

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%

answer

  1. searched newest first
  2. saturated is still active
  3. specific after general
  4. sequences retire earlier expectations

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.

solid answer

~40 s

For each call, GoogleMock walks the method's expectations from the **most recently declared** backwards and takes the first *active* one whose matchers accept the arguments. A saturated expectation is still active, so an extra call matching it fails as "called more times than expected" instead of falling through to an older one. Declaring `EXPECT_CALL(a, SetPower(100))` and then `EXPECT_CALL(a, SetPower(_)).Times(2)` therefore shadows the specific one: both calls hit the wildcard. Put the general expectation first. `.RetiresOnSaturation()` makes an expectation inactive once its upper bound is reached. Ordering is separate: by default calls may arrive in any order; an `InSequence` object makes the expectations declared in its scope match in order, while `Sequence` objects with `.InSequence(s1, s2)` or `.After(...)` express a partial order.

code

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

class Actuator {
 public:
  virtual ~Actuator() = default;
  virtual void SetPower(int percent) = 0;
};
class MockActuator : public Actuator {
 public:
  MOCK_METHOD(void, SetPower, (int percent), (override));
};
using ::testing::_;
using ::testing::AnyNumber;

TEST(Heater, SpecificFirstIsShadowed) {   // FAILS
  MockActuator a;
  EXPECT_CALL(a, SetPower(100));          // older, specific
  EXPECT_CALL(a, SetPower(_)).Times(2);   // newer, general: searched first
  a.SetPower(100);
  a.SetPower(40);
}  // "SetPower(100) ... Actual: never called - unsatisfied and active"

TEST(Heater, GeneralFirstWorks) {         // passes
  MockActuator a;
  EXPECT_CALL(a, SetPower(_)).Times(AnyNumber());
  EXPECT_CALL(a, SetPower(100));
  a.SetPower(100);
  a.SetPower(40);
}

go deeper

for a junior

Know that EXPECT_CALLs on the same method can overlap and that GoogleMock does not check call order unless asked.

for a middle

Explain newest-first matching and why the specific expectation must be declared after the general one.

for a senior

Diagnose shadowing and over-saturation from a failure log, and choose RetiresOnSaturation, InSequence or After for the real intent.

for a principal

Push teams to order only the calls whose order is part of the contract; fully sequenced tests make every reordering a breaking change.

## The matching rule When a mocked method is called, GoogleMock has to pick one expectation to charge the call to. The rule is short: 1. Consider only the expectations set on *this* method of *this* mock object. 2. Walk them in **reverse order of declaration**, newest first. 3. Skip any that are **retired**; stop at the first active one whose matchers accept the arguments. 4. If that expectation is already **saturated** (its upper bound is reached), the call is reported as an upper-bound violation: "called more times than expected". 5. If none matches, the call is unexpected and fails. The reverse order is deliberate. A fixture or a mock's constructor can set broad defaults, and the test body can then add narrower expectations that take precedence: newer rules override older ones. ## The shadowing trap The failing test in the example declares the specific expectation first: ```cpp EXPECT_CALL(a, SetPower(100)); // older EXPECT_CALL(a, SetPower(_)).Times(2); // newer, searched first ``` Both `SetPower(100)` and `SetPower(40)` match the newer wildcard, which absorbs them, so the specific expectation is never used and fails at destruction with "never called - unsatisfied and active". Swapping the two declarations, with the catch-all made `Times(AnyNumber())`, gives the intended meaning. The general rule from GoogleMock's introduction: **put the expectation with the more specific matchers after the general one**. ## Saturated is not retired An expectation does **not** retire automatically when it is full. With ```cpp EXPECT_CALL(a, SetPower(_)).Times(AnyNumber()); EXPECT_CALL(a, SetPower(100)); ``` a second `SetPower(100)` still matches the newer expectation, which is saturated, and the run fails as over-saturated rather than falling back to the catch-all. Adding `.RetiresOnSaturation()` (which must be the last clause) changes that: after its single call the expectation retires, and the next `SetPower(100)` is charged to the catch-all. The clause is meaningful only for an expectation with an upper bound. ## Order is a separate question By default the order in which calls arrive does not matter; any matching expectation can be used even if an earlier-declared one is unsatisfied. To require order there are three tools: - **`InSequence` object**: create `InSequence seq;` in a block, and every expectation declared while it lives must be matched in declaration order. Its constructor and destructor do the work, so the variable's name is irrelevant. - **`Sequence` objects with the `.InSequence(s1, s2)` clause**: each sequence is a chain, and an expectation can belong to several, which expresses a partial order (a DAG). - **`.After(e1, e2)`**: names prerequisite `Expectation` or `ExpectationSet` objects directly. An out-of-order call is reported as unexpected, with the message "the following immediate pre-requisites are not satisfied". A thermostat shutdown shows why a partial order is often the honest one. The heater must be switched off before the fan stops and before the log line is written, but the fan and the log may happen in either order: ```cpp Sequence fan_chain, log_chain; EXPECT_CALL(heater, SetPower(0)).InSequence(fan_chain, log_chain); EXPECT_CALL(fan, Stop()).InSequence(fan_chain); EXPECT_CALL(log, Write(HasSubstr("shutdown"))).InSequence(log_chain); ``` `SetPower(0)` belongs to both sequences, so it must come first; `Stop()` and `Write(...)` are each ordered only against it. Wrapping all three in one `InSequence` block would also pin the fan before the log, a constraint the product never asked for. Sequences also cause **retirement**. Once a later expectation in a sequence is matched, earlier ones in that sequence retire, so a call that would have matched them afterwards becomes an error. ## Summary | Situation | Result | |---|---| | Two active expectations match | the newest declared one is used | | The newest match is saturated | upper-bound failure, no fall-through | | It has `RetiresOnSaturation()` and is full | it is skipped; an older match is used | | Expectations in an `InSequence` scope | must be matched in declaration order | | No active expectation matches | unexpected call, test fails |

  • How would you express that the heater must be switched off before the fan stops, while other calls stay unordered?
    Use `.After()` or a `Sequence` on just those two expectations: `Expectation off = EXPECT_CALL(heater, SetPower(0)); EXPECT_CALL(fan, Stop()).After(off);`. Only that pair is ordered, and every other expectation stays unordered, which keeps the test from pinning incidental call order.
  • Why does GoogleMock search expectations newest first instead of in declaration order?
    So general defaults can be set first, in a mock's constructor or a fixture's set-up, and specialised by later, more specific expectations in the test body. Newest-first lets the later, narrower rule win. The cost is the shadowing trap: a general expectation declared after a specific one hides it.

  • Assuming the first declared EXPECT_CALL wins when two match
  • Thinking a saturated expectation automatically falls through to an older one
  • Believing calls must arrive in the order the EXPECT_CALLs are written
  • Putting RetiresOnSaturation before other clauses in the chain
  • Thinking InSequence orders every expectation in the test, not just its scope