Search code examples
c++unit-testinggoogletestgooglemock

How to write unit test for global functions where it is calling another global function using gtest/gmock in C++?


I have around 10 global functions in file. Need to write unit test cases for each of them. A global function could be called from another global function.

You can consider following three global functions.

int bar(int n){
    ..........
    //Could call another global function.
    ..........
}

int foo(int n){
    ..........
    int b = bar(x);
    ..........
}

int hut(int n){
    ..........
    ..........  
    int a = foo(x);
    ..........
    ..........  
    int b = hut(y);
    ..........
    ..........
}

In the time of testing hut(), function foo() and bar() should be mocked. Same thing could happens with foo() and bar() too. I am using gtest and gmock. Is it possible to do using gtest and gmock?

Thanks for reading.


Solution

  • If they are in the same file there sadly is no (sane) way to mock those Global Functions. Even if they are not, you would have a hard time doing this (e.g. modifying the original code to #include the mock headers instead of the real ones when building the code for unit testing), and it will not be pretty, so I'd strongly advise you against it.

    While there is a third party extension to add global mocking support, it only helps in the creation of the mock, but unfortunately not the "how do I get my functions to call the mock instead" issue.

    They cover this in this FAQ and even provide possible workarounds in their Blog - you can rewrite your code in a way to "get rid" of the static global function and making your code testable.

    In short: No, there is no good & easy way to mock global functions (especially if they call other globals), you may be better off refactoring the code into something more testable instead.