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.
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");
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?