Reputation: 1671
I have a C file contains some static functions, how to use google test to test those static function?
header file:
test.h
int accessData();
source file:
test.c
static int value;
static int getData()
{
return value;
}
int accessData()
{
if(value != 0)
{
return getData();
}
return 0;
}
static function is called by global function, but how to test those static function using google test?
Upvotes: 2
Views: 11081
Reputation: 30940
One way to achieve this is to #include
the C source file into your test source (if it's using only the subset of C that's valid C++). Then, the static
function is part of the same translation unit as the test code, and can be called from it:
#include "test.c"
/* here follow the tests of getData() */
The downside to this is that everything in test.c
gets compiled again, with obvious impact on build times. If that gets to be a problem, you might consider extracting the static functions to be tested into their own source file (e.g. test_p.c
, with the _p
meaning private/internal). Then #include "test_p.c"
from both test.c
and your unit test.
Upvotes: 5
Reputation: 25286
I understand that to test a function with google test, it must be visible to the test code. A static function is only visible to the current compilation unit.
A way to get around this is to "remove" the static attribute for test purposes:
#ifndef GOOGLE_TEST
# define STATIC static
#else
# define STATIC
#endif
STATIC int getData();
If this gives conflicts, for example because there aer getData()
functions in many source files, you could create simple container functions:
static int getData(<arglist>);
#ifdef GOOGLE_TEST
int myModule_getData(<arglist>) {return(getData(<arglist>);}
...
#endif
Upvotes: 6
Reputation: 134386
A static
function has it's visibility limited to the translation unit.
AFAIK, for googletest, you need to call the function(s) under test from a separate test file conating the test code written with TEST()
. If the function under test is static
, simply it is not possible to test that directly from the TEST()
MACRO invocation.
The straightway approach is to, comment out the static
modifier for the function for testing purpose.
Upvotes: -1