Question

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.

Was it helpful?

Solution 2

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
}

OTHER TIPS

The only answer I can give is the one from GMocks FAQ:

My code calls a static/global function. Can I mock it?

You can, but you need to make some changes.

In general, if you find yourself needing to mock a static function, it's a sign that your modules are too tightly coupled (and less flexible, less reusable, less testable, etc). You are probably better off defining a small interface and call the function through that interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly.

This Google Testing Blog post says it excellently. Check it out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top