Skip to content

Instantly share code, notes, and snippets.

@mister-good-deal
Created May 2, 2024 07:08
Show Gist options
  • Save mister-good-deal/51c03d26cb94e9f7c7e30313aa4a2165 to your computer and use it in GitHub Desktop.
Save mister-good-deal/51c03d26cb94e9f7c7e30313aa4a2165 to your computer and use it in GitHub Desktop.
Testing GMock mock methods injection
#include <gmock/gmock.h>
#include <gtest/gtest.h>
class MyClass {
public:
virtual ~MyClass() = default;
virtual void methodA() {
std::cout << "Base MyClass::methodA called\n"; // Confirming methodA execution
methodB();
}
virtual void methodB() {
std::cout << "Base MyClass::methodB called\n"; // Confirming methodB execution
methodC();
}
virtual void methodC() {
std::cout << "Base MyClass::methodC called\n"; // Confirming methodC execution
// Lambda function brakes the mock system !
[this]() { methodD(); };
methodD();
}
virtual void methodD() {
std::cout << "Base MyClass::methodD called\n"; // Confirming methodD execution
}
};
class MockMyClass final : public MyClass {
public:
MOCK_METHOD(void, methodA, (), (override));
MOCK_METHOD(void, methodB, (), (override));
MOCK_METHOD(void, methodC, (), (override));
MOCK_METHOD(void, methodD, (), (override));
void callRealMethodA() {
MyClass::methodA(); // Calls the actual implementation in the base class
}
void callRealMethodB() { MyClass::methodB(); }
void callRealMethodC() { MyClass::methodC(); }
};
TEST(MyClassTest, TestMethodAInvokesMockMethodB) {
MockMyClass mock;
// Expect methodA to be called and use a helper to invoke the real method
EXPECT_CALL(mock, methodA()).Times(1).WillOnce(testing::Invoke(&mock, &MockMyClass::callRealMethodA));
// When using Invoke(&mock, &MockMyClass::methodA), it fails to call the mocked method B
// Expect methodB to be called and use a helper to invoke the real method
EXPECT_CALL(mock, methodB()).Times(1).WillOnce(testing::Invoke(&mock, &MockMyClass::callRealMethodB));
// Expect methodC to be called and use a helper to invoke the real method
EXPECT_CALL(mock, methodC()).Times(1).WillOnce(testing::Invoke(&mock, &MockMyClass::callRealMethodC));
// Expect methodD to be mocked and define its behavior
EXPECT_CALL(mock, methodD()).Times(1);
mock.methodA(); // This call should trigger methodA's real implementation, which calls methodB, methodC, and methodD
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment