Testing static functions with CppUnit
Asked Answered
D

3

9

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?

Deteriorate answered 16/4, 2013 at 16:16 Comment(1)
Possible duplicate of How do I test a class that has private methods, fields or inner classes?Lacy
W
6

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.

Welfarism answered 16/4, 2013 at 16:24 Comment(1)
Thank you I have inspired a solution based on your answer. see my answer for more detailsDeteriorate
D
4

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.
Deteriorate answered 17/4, 2013 at 15:41 Comment(0)
L
1

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.

Lim answered 17/4, 2013 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.