Mocking with GMock
Mock dependencies.
Mocking with GMock is a free C++ Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Mock?
GMock creates fake objects that record calls and return programmed results. Mocking isolates the unit under test from slow or unpredictable dependencies like databases or networks.
Start with an Interface
Mockable dependencies are usually abstract base classes with virtual methods.
#include <string>
class Database {
public:
virtual ~Database() = default;
virtual std::string get(int id) = 0;
virtual bool save(const std::string& v) = 0;
};Defining a Mock Class
Use MOCK_METHOD to generate a mock for each virtual method, specifying return type, name, arguments, and qualifiers.
#include <gmock/gmock.h>
#include <string>
class Database {
public:
virtual ~Database() = default;
virtual std::string get(int id) = 0;
};
class MockDatabase : public Database {
public:
MOCK_METHOD(std::string, get, (int id), (override));
};Setting Expectations
EXPECT_CALL states how a mock method should be called and what it returns. WillOnce(Return(...)) programs the result.
#include <gmock/gmock.h>
using ::testing::Return;
TEST(DbTest, ReturnsValue) {
MockDatabase db;
EXPECT_CALL(db, get(1)).WillOnce(Return("alice"));
EXPECT_EQ(db.get(1), "alice");
}Argument Matchers
Expectations can match arguments loosely with matchers like _ (any), Gt(5), or HasSubstr("x").
#include <gmock/gmock.h>
using ::testing::_;
using ::testing::Return;
TEST(DbTest, AnyId) {
MockDatabase db;
EXPECT_CALL(db, get(_)).WillRepeatedly(Return("x"));
EXPECT_EQ(db.get(99), "x");
}Cardinality
Specify how many times a call is expected with Times.
Times(1)exactly onceTimes(AtLeast(2))Times(0)must never be called
#include <gmock/gmock.h>
using ::testing::AtLeast;
using ::testing::Return;
TEST(DbTest, CalledTwice) {
MockDatabase db;
EXPECT_CALL(db, get(1)).Times(AtLeast(2)).WillRepeatedly(Return("v"));
db.get(1);
db.get(1);
}Return Actions
Actions decide behavior.
Return(value)ReturnRef(ref)Throw(exception)Invoke(callable)to run custom code
Injecting the Mock
The unit under test must accept the dependency through a pointer or reference to the interface. This is dependency injection, and it is what makes mocking possible.
#include <string>
class Database;
class UserService {
Database& db;
public:
UserService(Database& d) : db(d) {}
std::string name(int id);
};Verifying Interactions
GMock verifies all EXPECT_CALL expectations when the mock is destroyed. Unmet expectations (wrong count or missing calls) fail the test automatically.
Nice, Strict, Naggy Mocks
Control how unexpected calls are treated.
NiceMock: ignore uninteresting callsStrictMock: any unexpected call fails- Default (naggy): warns on uninteresting calls
Mock Only What You Own
Prefer mocking your own interfaces, not third-party concrete classes. Introduce thin wrapper interfaces around external libraries so tests stay stable.
Quick Check
Recall when GMock checks expectations.
Recap
You learned GMock.
- Mock virtual interfaces with
MOCK_METHOD EXPECT_CALL+ actions program behavior- Matchers and
Timescontrol arguments and cardinality - Inject mocks; expectations verified at destruction
Frequently asked questions
Is the “Mocking with GMock” lesson free?
Yes — the full text of “Mocking with GMock” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.
What will I learn in “Mocking with GMock”?
Mock dependencies. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C++ Academy?
No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Mocking with GMock” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C++ Academy lesson?
Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Setting Up GTest
- Assertions and Matchers
- Fixtures and Setup
- Mocking with GMock