In GoogleMock, how do you mock a dependency whose member functions are not virtual, and what must change in the code under test?
answer
- high-performance dependency injection
- unrelated class, same signatures
- choose the type at compile time
- hiding is not overriding
basics
~20 sWrite 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.
solid answer
~40 sGoogleMock can only intercept a call it is routed to. With a virtual interface, routing happens at run time through the base class; with non-virtual members it must happen at **compile time**. The cookbook's "hi-perf dependency injection" recipe: write `MockSensor` with `MOCK_METHOD(double, ReadCelsius, (), (const))` (no `override`, no base class), and make the consumer a template, `template <class Sensor> class Thermostat`, used as `Thermostat<I2cSensor>` in production and `Thermostat<MockSensor>` in tests. The mock only needs the members the template actually calls. Deriving the mock from the concrete class does **not** work: the mock member hides the base one, and code holding an `I2cSensor&` still calls the real function. Free functions can't be mocked directly; wrap them behind an interface, or pass a `std::function` and use `MockFunction`.
code
cpp · 31 lines#include <gmock/gmock.h>
#include <gtest/gtest.h>
class I2cSensor { // production type: nothing is virtual
public:
double ReadCelsius() const { return 21.0; /* real bus read */ }
};
class MockSensor { // unrelated class, same signature
public:
MOCK_METHOD(double, ReadCelsius, (), (const)); // no override
};
template <class Sensor> // the type is chosen at compile time
class Thermostat {
public:
explicit Thermostat(const Sensor& s) : s_(s) {}
bool HeaterWanted(double target) const { return s_.ReadCelsius() < target; }
private:
const Sensor& s_;
};
using ::testing::Return;
TEST(Thermostat, ColdThenWarm) {
MockSensor sensor;
EXPECT_CALL(sensor, ReadCelsius()).WillOnce(Return(17.0)).WillOnce(Return(23.0));
Thermostat<MockSensor> t(sensor); // production uses Thermostat<I2cSensor>
EXPECT_TRUE(t.HeaterWanted(20.0));
EXPECT_FALSE(t.HeaterWanted(20.0));
}go deeper
Know that ordinary GoogleMock mocks override virtual functions, so a non-virtual dependency needs a different approach.
Explain the unrelated-mock plus template recipe and why hiding a base member does not intercept calls.
Choose between an interface, a template seam and a std::function seam from profiling evidence and build-time cost.
Set where performance-driven seams are allowed so hot-path code stays testable without making every class a template.
## Why non-virtual is a problem at all A GoogleMock mock works by **overriding** a virtual function: the code under test calls `sensor.ReadCelsius()` through an `ISensor&`, dynamic dispatch lands in the mock's generated member, and GoogleMock records the call. A non-virtual member function is bound at compile time to the static type of the expression, so there is no run-time hook to redirect. Game engines, trading systems and embedded code often avoid virtual calls on hot paths, so the question comes up in exactly the teams that write C++ for performance. ## The recipe: an unrelated mock plus a template GoogleMock's cookbook calls this **hi-perf dependency injection**: 1. Write a mock class that is *unrelated* to the real one: no base class, just `MOCK_METHOD` members with the same signatures. Leave out `override`, since there is nothing to override. 2. Make the code under test a **template** on the dependency type, so the choice happens at compile time. 3. Instantiate it with the real class in production (`Thermostat<I2cSensor>`) and with the mock in tests (`Thermostat<MockSensor>`). The mock only needs the members the template actually uses; the cookbook's example mocks two of a packet stream's three members. Expectations, matchers and actions work exactly as on any other mock, as the example shows. ## Two tempting shortcuts that fail - **Deriving the mock from the concrete class.** `class MockSensor : public I2cSensor` with `MOCK_METHOD(double, ReadCelsius, (), (const))` compiles, but the generated member only **hides** the base one. Code that receives a `const I2cSensor&` calls `I2cSensor::ReadCelsius()`, the real hardware read, and the expectation fails as "never called". Run as a test, the call returns the real 21 where the expectation set up the mocked 5. - **Adding `override` to force it.** On a non-virtual base member the compiler rejects it; clang 21 prints `error: only virtual member functions can be marked 'override'`. ## Free functions and static members The cookbook is explicit that a free function, C-style or `static`, cannot be mocked directly. The options: - introduce an interface with a virtual `Open()` or `Read()` and a thin concrete class that calls the free function, then mock the interface; related functions can share one interface so the overhead is small; - combine that interface with the template recipe above when profiling shows the virtual call matters; - accept a `std::function` instead of calling the function directly, and use `MockFunction<double()>` in the test, whose `AsStdFunction()` produces the callable. The `std::function` seam is the smallest change when only one function is involved: ```cpp int ReadRaw(const std::function<int(int)>& i2c_read) { return i2c_read(0x48); } TEST(Sensor, ReadsTheRightRegister) { testing::MockFunction<int(int)> i2c_read; EXPECT_CALL(i2c_read, Call(0x48)).WillOnce(testing::Return(17)); EXPECT_EQ(ReadRaw(i2c_read.AsStdFunction()), 17); } ``` In production, the caller passes the real `i2c_read` function; `MockFunction`'s single mocked member is named `Call`, so expectations are written against it. ## Trade-offs to state in an interview | Approach | Cost in production | Cost in the codebase | |---|---|---| | Virtual interface | one indirect call per use | an interface per dependency | | Template on the dependency | none at run time | code moves into headers, longer builds, template error messages | | `std::function` seam | a type-erased call | callers must pass the function | The cookbook also argues against the reflex of simply making the concrete class's functions virtual so it can be mocked: a virtual function is an extension point that weakens control over the class's invariants. Prefer an interface you own on top of the concrete class, and reach for the template recipe when the call is genuinely hot. `NiceMock` and `StrictMock` can wrap such a mock too, but the reference warns that they might not work correctly when the mock's destructor is not virtual, and an unrelated mock class like this one has a non-virtual destructor unless you declare one.
- The code under test calls a C function, i2c_read(), directly. How do you get a GoogleMock seam around it?You cannot mock the free function itself. Either introduce an interface whose concrete implementation calls `i2c_read()` and mock that interface, or change the code to take a `std::function<int(int)>` and pass `mock.AsStdFunction()` from a `MockFunction<int(int)>` in the test. Both move the call behind something the test can replace.
- What does the template recipe cost a team that adopts it widely?The consumer's code moves into headers or explicit instantiations, so builds get slower and every change recompiles more translation units. Compiler errors become template errors, and each consumer class is instantiated twice, once with the real type and once with the mock. It is worth it on hot paths, not as a default.
- Deriving the mock from the concrete class and expecting calls through a base reference to reach it
- Adding override to a mock of a non-virtual member
- Declaring MOCK_METHOD at namespace scope to mock a free function
- Making every concrete method virtual just so tests can mock it
- Thinking the mock must declare every member of the real class