Mocking free function

前端 未结 4 517
我在风中等你
我在风中等你 2020-11-27 06:10

I am stuck in a problem and can\'t seem to find the solution.

I am using VS2005 SP1 for compiling the code.

I have a global function:

A* foo(         


        
4条回答
  •  情歌与酒
    2020-11-27 07:10

    Of course, the answer explaining the solution according to GTest/GMock's documentation couldn't be much more correct.

    But I would like to add a temporary quick&dirty approach. It should be applicable to cases where you want to get legacy C/C++ code under test as quickly and as non-invasively as possible. (Just to proceed with fixes, refactoring and more proper testing as soon as possible after.)

    So, to mock a free function void foo(int) appearing in some code to be tested, within the source file you just make the following adaptions:

    #if TESTING
    #define foo(param) // to nothing, so calls to that disappear
    #endif
    
    // ... code that calls foo stays untouched and could be tested
    

    The macro TESTING, indicating that the code runs under test, doesn't come with GTest/GMock - you need to add it to test targets by yourself.

    The possibilities are rather limited, but you might also be able to construct something useful for return types as A* in the question's example.

    Unfortunately, also this isn't a solution without changing the code. If that is really necessary, you could Google for 'link seams'. But my guess is that this could be quite a hassle in practice. And it even might not be possible at all in many/most cases?!

提交回复
热议问题