Unit test simplified in C - Criterion
Introduction
Unit testing is crucial in software development, verifying individual code components function as expected. Criterion is a popular unit testing framework for C programming, providing a simple API for writing and running tests.
Criterion
Criterion is a modern, open-source unit testing framework for C, offering a range of features including test suites, cases, and assertions. Its intuitive API makes it an ideal choice for C developers.
How to install
Check the Github.
If you're on Debian/Ubuntu: apt-get install libcriterion-dev
. Anything else please find the correct method in the Github page.
How to use
Create exercise.c
Contains the functions we want to test:
// exercise.c
int add(int a, int b)
{
return a + b;
}
int subtract(int a, int b)
{
return a - b;
}
float get_average(int x, int y, int z)
{
return ((float) x+y+z) / 3;
}
int multiply(int x, int y)
{
return x * y;
}
Create exercise.h
This is the header file:
// exercise.h
int add(int a, int b);
int subtract(int a, int b);
float get_average(int x, int y, int z);
int multiply(int x, int y);
Create main.c
The main test file:
// main.c
#include "exercise.h"
#include <criterion/criterion.h>
Test(add, basic)
{
int result = add(1, 2);
cr_assert_eq(result, 3);
}
Test(subtract, description)
{
int result = subtract(10, 2);
cr_assert(result == 8, "10 - 2 is 8");
}
Test(get_average, basic)
{
float result = get_average(1, 2, 3);
cr_assert_eq(result, 2);
}
Test(get_average, double_equal)
{
float result = get_average(3, 4, 5);
// deliberately insert the wrong number
cr_assert_float_eq(result, 4.5, 0.01, "Avg of 3, 4, 5 is 4.0");
}
Test(multiply, expect_logWarn)
{
int result = multiply(3, 23);
cr_expect_eq(result, 67); // deliberately insert the wrong number
cr_log_warn("The result is supposed to be 69 *wink wink*");
}
Result
Directory structure
If you've followed the above instructions correctly, your directory structure should look like this:
Running the code
Use the usual compile and run command. Mine are:
Compile:
gcc -o main -O main.c exercise.c -lcriterion
Run:
./main
Note: don't forget we need to add exercise.c in the compile command
Note: the failed tests were deliberately done to show the fail messages
Conclusion
In this article, we demonstrated how to use Criterion for unit testing in C. With its simple API, Criterion makes testing super easy and more enjoyable! Granted it's not as easy and trivial as unit testing in Zig, but using Criterion is the most comfortable method of testing in C that I know of.
For example another popular C library for testing: munit is not as easy to use and contains a load of boilerplates...yuck!