Google Mock: Is it ok to use global mock objects?

早过忘川 提交于 2019-12-05 18:17:07

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 UTs 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.

In addition to the accepted answer, if you're using GTest, global variables will also be tagged as leakage when they're not destroyed after test cases are executed. The idea behind leakage is in this reference: https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#forcing-a-verification

If you don't want manual verification, the closest solution would be to have the mock object as a member of your fixture class. And if for some reason you would need to dynamically allocate mock, you can have a pointer and create/destroy the instance on SetUp and TearDown (the same concept as @Chris Olsen's answer). Or if you're in C++11, you can use shared_ptr:

class Fixture : public ::testing::Test 
{  
    std::shared_ptr<ObjT> mPtr;
    ...
    void SetUp()
    {
        mPtr = std::make_shared<ObjT>();
    }
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!