Google Mock: Is it ok to use global mock objects?
You can, but it is not a good idea.
Doing such a thing is violate the isolation principle of UT
.
This violation may cause an unexpected failure/pass in your tests.
Gtest
uses the destructor of the fake objects to verify that the expectation occurred, this is the reason behind the expectation that each fake object will create and release in the body of the test, or within a test fixture class.
If you make the fake object global then it won't release at the end of each UT
, then the verification won't execute and the test will pass even when it should fail. more over some of your UT
s may fass/fail when you execute all your tests together; in one test you expect the method x
won't call and in the other you expect that the method will call; in one UT you expect the method x will call 3 times, but the method was call twice in the test + one in other test(the test should fail but it won't...)
So the bottom line you should never use a global mock unless this global mock is being in use only to prevent null pointer(you didn't set a behaviour..)
Just stumbled across this question while chasing a bug related to my mock objects. In my case the problem was that the mock object's constructor was being called before InitGoogleMock
, and that seemed to send things off into the weeds.
Note: I'm using Google Mock with CppUnitTestFramework.
Fail:
MockObject mock;
TEST_MODULE_INITIALIZE(ModuleInitialize)
{
InitGoogleMock(argc, argv);
}
Win:
MockObject *mock = nullptr;
TEST_MODULE_INITIALIZE(ModuleInitialize)
{
InitGoogleMock(argc, argv);
mock = new MockObject;
}
TEST_MODULE_CLEANUP(ModuleCleanup)
{
delete mock;
}
Not saying it's best practice or anything, but if you need global mock objects I'd say pay attention to when your constructors are being called.