Unit Testing with C

What is Unit Testing?

Unit Testing of software applications is done during the development (coding) of an application.

The objective of Unit Testing is to isolate a section of code and verify its correctness. In procedural programming a unit may be an individual function or procedure

The goal of Unit Testing is to isolate each part of the program and show that the individual parts are correct. Unit Testing is usually performed by the developer.

Check framework

Check is a unit testing framework for C. It features a simple interface for defining unit tests, putting little in the way of the developer. Tests are run in a separate address space, so both assertion failures and code errors that cause segmentation faults or other signals can be caught.

How to Write a Test

Test writing using Check is very simple. The file in which the checks are defined must include ‘check.h’ as so:

#include <check.h>

// The basic unit test looks as follows:

START_TEST (test_name)
 // unit test code

The START_TEST/END_TEST pair are macros that setup basic structures to permit testing. To run unit tests with Check, we must create some test cases, aggregate them into a suite, and run them with a suite runner.

// define test suite and cases
Suite *test_suite(void) {

	Suite *s = suite_create("example-sha2");
	TCase *tc;

  tc = tcase_create("sha2");
  tcase_add_test(tc, test_sha1);
  tcase_add_test(tc, test_sha256);
  tcase_add_test(tc, test_sha512);
  suite_add_tcase(s, tc);