ReviseAlgo Logo

Testing in C++

Mocking with Google Mock

Isolate classes under test using GMock to write mocks, stubs, and expectations.

Interview: Using MOCK_METHOD macros, setting expectations before executions, and mock actions.

Last Updated: June 13, 2026 9 min read

Google Mock (GMock) is an extension of GTest used to write mock classes. It allows you to isolate dependencies (like databases or networks) to test your code in isolation.

MOCK_METHOD

A macro used to define mock methods on interface classes, specifying the return type, name, and parameters.

EXPECT_CALL

Sets expectations on mock methods, specifying call counts and expected argument values.

Mock Actions

Specify what a mock method returns or does using actions like Return(val) or Invoke(func).

The Ordering Rule in GMock

A common pitfall is setting expectations after executing the code under test. In GMock:

Execution Order

Always write your EXPECT_CALL definitions before invoking the methods under test. GMock matches method calls against these active expectations as they occur, throwing errors if unexpected calls are made.

Code Walkthrough

A mock implementation of a database connection interface using GMock.

Interview-Relevant Information

Q: What is the difference between Mocking and Stubbing in GMock?
Answer: Stubs provide canned responses to method calls made during the test. Mocks verify that the code under test makes specific calls to the mock object, checking both the call count and the arguments passed.

Q: How do you mock a const member function using MOCK_METHOD?
Answer: Specify the const qualifier in the method attributes block (the fourth argument of the macro): MOCK_METHOD(int, getValue, (), (const, override)).

Quick Checklist

Did you declare your expectations before executing the test code? Did you specify virtual destructors in the mocked interface? If yes, your mocks are configured correctly.

Use Cases

Isolating network API clients to test application behavior under poor connection states.

Mocking hardware access layers in embedded software suites.

Common Mistakes

Writing EXPECT_CALL definitions after executing the code under test.

Forgetting to specify virtual destructors on mocked interfaces, which can result in memory leaks during deletion.