How to test a static function

Can you give more information as to why you can't call the function?

Is it not available because it's private to a .c file? If so, you're best bet is to use conditional compilation that allows for access to the function in order to allow for other compilation units to access it. For example

SomeHeaderSomewher.h

#if UNIT_TEST
#define unit_static 
#else
#define unit_static static
#endif

Foo.h

#if UNIT_TEST
void some_method
#endif

Foo.cpp

unit_static void some_method() ...

I have a test harness. In dire cases - like trying to test a static function, I use:

#include "code_under_test.c"
...test framework...

That is, I include the whole of the file containing the function under test in the test harness. It is a last resort - but it works.


For unit tests, we actually have the test code within the source file itself and we conditionally compile it in when testing. This gives the unit tests full access to all functions and file-level variables (static or otherwise).

The unit tests themselves are not static - this allows us to call the unit tests from a single super-test program which unit tests all compilation units.

When we ship the code, we conditionally compile out the unit tests but this isn't actually necessary (if you want to be certain you're shipping exactly the same code you tested).

We've always found it invaluable to have the unit tests in the same place as the code you're testing since it makes it more obvious that you need to update the tests if and when the code changes.

Tags:

C

Unit Testing