How do I mock dependencies in C++?

Mocking dependencies in C++ is a common practice to isolate the unit being tested and control the behavior of its dependencies. This allows developers to test components in isolation without relying on the actual implementations of their dependencies.

Example of Mocking Dependencies in C++

In this example, we will demonstrate how to use the Google Mock framework to mock a dependency in C++. Assume we have a simple application with a service that relies on a database interface.

#include #include // The interface that we want to mock. class Database { public: virtual ~Database() {} virtual std::string GetData(int id) = 0; }; // The class under test. class DataService { public: DataService(Database* db) : database(db) {} std::string GetRecord(int id) { return database->GetData(id); } private: Database* database; }; // Mock class. class MockDatabase : public Database { public: MOCK_METHOD(std::string, GetData, (int id), (override)); }; TEST(DataServiceTest, GetRecordReturnsDataFromDatabase) { MockDatabase mockDatabase; DataService dataService(&mockDatabase); EXPECT_CALL(mockDatabase, GetData(1)).WillOnce(::testing::Return("MockData")); std::string result = dataService.GetRecord(1); ASSERT_EQ(result, "MockData"); }

Mocking C++ Google Mock Unit Testing Dependencies