Rand0m
Rand0m

Reputation: 372

Check Unit testing in C: Best way to test static methods

I am using Check framework do to unit testing of my C code, and I couldn't find a proper way to test the static methods.

My work around, is not ideal at all and would like if someone can point me in the right direction on how to do it properly. My work around is simply by add #ifdef macro that changes the static methods to extern in case I pass -D DEBUG at compile time.

In the source file

#ifdef DEBUG
unsigned ds_roundup_to_prime (const unsigned bsize) {
#else
static inline unsigned ds_roundup_to_prime (const unsigned bsize) {
#endif

And in the header file I do

#ifdef DEBUG
unsigned ds_roundup_to_prime (const unsigned bsize);
#endif

Ideally source code shouldn't change to cater for unit tests. Unit-test framework, should must be capable of testing the source code as it will look in production.

Thanks

Upvotes: 3

Views: 2471

Answers (2)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137527

It's debatable whether or not static functions should be tested, as they aren't part of the public API.

I test static functions by including the unit-under-test, rather than linking against it:

foo.c (Unit under test)

static int foo(int x)
{
    return x;
}

/* ... */

test_foo.c

#include "foo.c"

void test_foo(void)
{
    assert( foo(42) == 42 );
}

int main(void)
{
    test_foo();
}

Compile just that test:

$ gcc -Wall -Werror -o test_foo test_foo.c
$ ./test_foo

Upvotes: 6

Fiddling Bits
Fiddling Bits

Reputation: 8861

I test static functions in the following manner.

I have a header file called utility.h. It has the following definition:

#ifdef UNIT_TEST
  #define UTILITY_STATIC(DECLARATION) extern DECLARATION; DECLARATION
#else
  #define UTILITY_STATIC(DECLARATION) static DECLARATION
#endif

Every source file that has functions that are to be tested are declared as such:

#include "utility.h"
UTILITY_STATIC(void function(void));
UTILITY_STATIC(void function(void))
{
}

I have an additional header file (e.g. test_helper.h), used in the unit test executable, that has the line:

extern void function(void);

In this way, tests have access to function whereas source files that don't define UNIT_TEST do not.

Note

This can be used for static variables as well.

Upvotes: 3

Related Questions