Sometimes I find myself doing coding tests to keep my problem-solving skills sharp. One of the platforms I use is CodeWars, a platform owned by Andela. My current stack is JavaScript (including NodeJS), PHP, and C/C++. I noticed the tests for the C and C++ exercises were written using a library called Criterion, which brings us to the topic of Unit testing in C and C++. I did some intense C and C++ work a while back on embedded Linux systems and one of the tools I lacked was a simple library to do testing in. Looking at the criterion I realized I had just found an easy-to-use tool for testing my C/C++ work.
I decided to put this simplicity to test and in order to do so I decided to use a toy CLI app I wrote in C some years ago. This app has a function for random number generation.
In file app.c:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<string.h>
#include "app.h"
........
int generateAccountNumber(){
srand(time(NULL));
return rand();
}
........
Testing this is as simple as the code below:
In file tests.c:
#include <stdio.h>
#include <criterion/criterion.h>
#include "app.h"
#include <string.h>
#define DETERMINE_TYPE(x) _Generic((x), \
int: "int", \
float: "float", \
double: "double", \
char: "char", \
long: "long", \
default: "unknown")
Test(bankapp, random_num) {
cr_assert(!strcmp("int", DETERMINE_TYPE(generateAccountNumber())));
}
All you need to do now is compile the test using:
gcc tests.c app.c -o tests -lcriterion
One thing to note is that the main function of the application you are testing must be in a separate file to prevent clashing with the main file provided by the Criterion testing framework. And that is it! You have a test.
I added the C11 _Generic macro feature to highlight a new C language feature that allows you to “return” a select value or function based on the type provided. This can be used for implementing programming features such as function overloading, Generics, Type checking like I used here, and many more. We will be looking more into this C11 feature in future articles. Thanks for reading.
References
Leave a Reply