CUnit

As the name says CUnit is an xUnit implementation for the C programming language.

In comparison to dynamic programming languages the test organization requires much more manual glue code. Because C has no introspection one has to register every test case manually. Likewise there is no support for utilities like mock object generation or annotations.

On the other hand unit tests can be very useful in C, for example when implementing data structures. Test cases may isolate null pointer dereferencing and one can use valgrind on them to detect memory leaks at the lowest level.

A very simple code example looks like this:

#include "CUnit/Basic.h" 
#include "mylib.h" 
 
void testMac_cmp() {
    MAC_t a = {{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}};
    MAC_t b = {{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}};
    MAC_t c = {{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe}};
    CU_ASSERT(mac_cmp(&a, &b) == 0);
    CU_ASSERT(mac_cmp(&a, &c) > 0);
    CU_ASSERT(mac_cmp(&c, &a) < 0);
}
 
int main() {
    CU_pSuite pSuite = NULL;
    CU_initialize_registry();
 
    /* Add a suite to the registry */
    pSuite = CU_add_suite("data_mac", testMac_init_suite, NULL);
 
    /* Add the tests to the suite */
    CU_add_test(pSuite, "testMac_cmp", testMac_cmp);
    // ...
 
    /* Run all tests using the CUnit Basic interface */
    CU_basic_set_mode(CU_BRM_VERBOSE);
    CU_basic_run_tests();
 
    CU_cleanup_registry();
    return CU_get_error();
}

After compiling the test program (here including a failed test) can be executed. With the selected verbose console output the result is:

~/spp_ipv6/tests> ./unittests
     CUnit - A Unit testing framework for C - Version 2.1-0
     http://cunit.sourceforge.net/
 
Suite: unittest_data_mac
  Test: testMac_cmp ... FAILED
    1. tests/unittest_data_mac.c:95  - mac_cmp(&a, &b) == 0
  Test: testMac_eq ... passed
  Test: testMac_cpy ... passed
  Test: testMac_IS_MAC ... passed
  Test: testMac_parse ... passed
  Test: testMac_str ... passed
  Test: testMac_set ... passed
...
 
--Run Summary: Type      Total     Ran  Passed  Failed
               suites        5       5     n/a       0
               tests        41      41      40       1
               asserts     632     632     631       1

Comments are closed.