Created
May 2, 2024 07:08
-
-
Save mister-good-deal/51c03d26cb94e9f7c7e30313aa4a2165 to your computer and use it in GitHub Desktop.
Testing GMock mock methods injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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