C++
Mock
Learn to use fake objects with GoogleMock.
What is GoogleMock?
GoogleMock (gmock) is a mock object framework bundled with GoogleTest. It lets you write mock classes that imitate a real dependency (database, network, file). This separates tests from slow or brittle dependencies.
A mock class inherits from the interface it imitates. The MOCK_METHOD macro creates a fake implementation for each virtual method. EXPECT_CALL(mock, method(...)) sets call expectations and return values. Example: mocking a Database interface's get method lets you test behavior without a real database.
Writing a mock class
To write a mock class you first define the real interface (with pure virtual methods). Then the mock class inherits from it and calls MOCK_METHOD for each method. MOCK_METHOD takes four parts: return type, method name, argument list (in parens), qualifiers (override).
Example: class MockDatabase : public Database { public: MOCK_METHOD(int, get, (const std::string& key), (override)); };. Here the get method is mocked. In a test you create MockDatabase db; and set EXPECT_CALL(db, get("id")).WillOnce(Return(42));. Then db.get("id") returns 42; no real database is needed.
Exercise Write a MockDatabase
Define a Database interface with virtual ~Database() = default; and virtual int get(const std::string& key) = 0;. Derive MockDatabase from Database and call MOCK_METHOD(int, get, (const std::string& key), (override));. In main print std::cout << "test: ready";.
Show example solution
#include <iostream>
#include <gtest/gtest.h>
#include <string>
class Database {
public:
virtual ~Database() = default;
virtual int get(const std::string& key) = 0;
};
class MockDatabase : public Database {
public:
MOCK_METHOD(int, get, (const std::string& key), (override));
};
int main(int argc, char** argv) {
std::cout << "test: ready";
return 0;
}
Test yourself
-
Complete the MOCK_METHOD macro
____(int, get, (const std::string& key), (override));
Show answer
MOCK_METHOD(int, get, (const std::string& key), (override));
-
Match each piece to its role
- MOCK_METHOD
- Creates a fake method
- EXPECT_CALL
- Sets a call expectation
- class MockDatabase
- The mock class
- WillOnce(Return(42))
- Sets the return value
-
What does EXPECT_CALL do?
- Sets an expectation on a mock method call
- Stops the test immediately
- Creates a new mock class
- Colors the output
Show answer
Sets an expectation on a mock method call — EXPECT_CALL sets how a mock method should be called and what it returns.
Next lesson: Summary - Testing basics