Mocking
A mock is a test double you configure with expected calls and return values. In C++ that usually means a virtual interface plus gMock (MOCK_METHOD). Prefer a hand-written fake when the interaction is simple.
Detailed Explanation
You are testing a Reporter that calls HttpClient::post. You do not want the test on the network. You inject an HttpClient interface. In production, a real client implements it. In the test, a mock records post and returns a canned body.
gMock (ships with GoogleTest) generates the recording:
class MockHttp : public HttpClient {
public:
MOCK_METHOD(std::string, post, (const std::string& url), (override));
};
EXPECT_CALL(mock, post("https://x")).WillOnce(Return("{}")); sets the contract. After the test, gMock fails if the call was missing or the arguments did not match. NiceMock suppresses unexpected-call warnings; StrictMock fails on them.
C++ mocks need a seam. Templates (Reporter<Http>) can take a fake type without virtuals. Free functions are hard to mock; wrap them. final classes and non-virtual methods cannot be gMocked without a wrapper.
A fake is a working small implementation (map as a store). A stub returns canned data. A mock also asserts how it was called. Over-mocking (every interaction is EXPECT_CALL) makes tests brittle. Fake the store; mock the payment gateway if you must assert "we charged once".
Catch2 users pair Catch2 with trompeloeil or FakeIt, or they write fakes. The design rules are the same.
Lifetime: the mock must outlive the code under test if that code stores a pointer. EXPECT_CALL objects must stay alive until the call happens.
Do not mock types you do not own (std::ifstream) — wrap them. Do not mock a concrete User value; construct one.
Code Examples
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>
struct HttpClient {
virtual ~HttpClient() = default;
virtual std::string post(const std::string& url) = 0;
};
struct Reporter {
HttpClient& http;
std::string ping() { return http.post("https://x/ping"); }
};
class MockHttp : public HttpClient {
public:
MOCK_METHOD(std::string, post, (const std::string& url), (override));
};
TEST(Reporter, Pings) {
MockHttp http;
EXPECT_CALL(http, post("https://x/ping"))
.WillOnce(::testing::Return("ok"));
Reporter r{http};
EXPECT_EQ(r.ping(), "ok");
}Common Gotchas
Mocking a non-virtual method
gMock will not dispatch. Add a virtual interface or a template seam.
Over-specified `EXPECT_CALL`
argument matchers that include timestamps will flake. Match the stable parts.
Unexpected calls fail `StrictMock`
start with a fake if you only need data.
The mock dies before the unit
use-after-free, not a nice gMock error. Declare the mock first.