Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing static functions with CppUnit

My project contains C files. And in some files I have functions defined as static.

I'm using CppUnit in my unit tests and I want to test these static functions. I know that calling a function from outside the file (where it's defined) is not allowed. Is there a solution to avoid this problem in order to call these static functions from my C++ test file?

like image 713
MOHAMED Avatar asked Apr 16 '13 16:04

MOHAMED


3 Answers

I have a common header file that I include in all the source files of my projects. I have added these lines and the problem is solved:

#ifdef TEST
#define static
#endif

I can even avoid adding the above code in my origin C code. I could add the flag -Dstatic= in the gcc command and I find this works as well.

But we have to be careful when using this solution because:

  • We can have the same variable/function name defined as static in 2 separate files.
  • We can have a function which contains a variable defined as static.
like image 45
MOHAMED Avatar answered Oct 05 '22 10:10

MOHAMED


Assuming we are talking about C static functions then the easiest solution to this is to make the functions non-static when you are compiling a debug build. This means the symbols will be available for you to use in your unit tests. This only works if there is no aliasing of symbols though.

If you define the symbol DEBUG on all debug builds then something like:

#ifdef DEBUG
#define debug_export 
#else
#define debug_export static
#endif

and then define your static functions like this

debug_export void foo(void)
{
...
}

and either include the declarations conditionally in the header file or manually import them in your unit test file:

extern void foo(void);

Other ways around it are to either include the unit tests in the source file itself (a bit of a mess if it gets out of hand), not bother unit testing the function (a bit of a cop-out) or to mark the function as dll-local rather than static and ensure that your unit tests are part of that dynamic object.

like image 112
Will Avatar answered Oct 05 '22 11:10

Will


Is there any way to refactor the code to remove the need for static methods? From an OO design point of view, statics are globals in sheep's clothing.

I know it's not necessarily the practical or quickest answer, but you would improve your design by eliminating it.

like image 22
John Deters Avatar answered Oct 05 '22 09:10

John Deters