Search code examples
c++static-methodsgoogletestgooglemocknon-member-functions

Mocking static functions declared and defined in .cpp without class file using GMOCK


file.h
int func(int);

file.cpp
static int call();
static void print(int x);

int func(int) {
    int val = call();
    print(val);
}

Here static functions are declared and defined in the same file file.cpp. I have not included definition of static functions here. Now using GMock I need to mock or test all the functions defined in .h and .cpp.


Solution

  • Since those two functions are hidden, you have no ways to test them, other then calling the func function.

    That means, you can not mock the calls to ´call´ and ´print´ functions.

    The only way would be to somehow unhide those two functions, or at least change the way you call them.

    If you create function callback variables in your header, and call them instead of the real functions, then you can mock those calls. Something like this (not tested) :

    file.h
    typedef void call();
    namespace hidden{
    extern call callCb;
    }
    int func(int);
    
    file.cpp
    namespace{
    void call(){
    //do stuff
    }
    }
    namespace hidden{
    call callCb=::call;
    }
    int func(int){
      hidden::callCb();
      // do things
    }