Unit testing opaque structure based C API

Posted by Nicolas Goy on Stack Overflow See other posts from Stack Overflow or by Nicolas Goy
Published on 2009-12-27T07:31:37Z Indexed on 2010/03/28 16:23 UTC
Read the original article Hit count: 303

Filed under:
|
|

I have a library I wrote with API based on opaque structures. Using opaque structures has a lot of benefits and I am very happy with it.

Now that my API are stable in term of specifications, I'd like to write a complete battery of unit test to ensure a solid base before releasing it.

My concern is simple, how do you unit test API based on opaque structures where the main goal is to hide the internal logic?

For example, let's take a very simple object, an array with a very simple test:

WSArray a = WSArrayCreate();
int foo = 5;
WSArrayAppendValue(a, &foo);
int *bar = WSArrayGetValueAtIndex(a, 0);

if(&foo != bar)
    printf("Eroneous value returned\n");
else
    printf("Good value returned\n");

WSRelease(a);

Of course, this tests some facts, like the array actually acts as wanted with 1 value, but when I write unit tests, at least in C, I usualy compare the memory footprint of my datastructures with a known state.

In my example, I don't know if some internal state of the array is broken.

How would you handle that? I'd really like to avoid adding codes in the implementation files only for unit testings, I really emphasis loose coupling of modules, and injecting unit tests into the implementation would seem rather invasive to me.

My first thought was to include the implementation file into my unit test, linking my unit test statically to my library.

For example:

#include <WS/WS.h>
#include <WS/Collection/Array.c>

static void TestArray(void)
{
    WSArray a = WSArrayCreate();
    /* Structure members are available because we included Array.c */
    printf("%d\n", a->count);     
}

Is that a good idea?

Of course, the unit tests won't benefit from encapsulation, but they are here to ensure it's actually working.

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about c