For unit testing C code, we use the MUnit framework.
There are many different assert types you can use in your tests, but the main one is munit_assert().
For an example, lets take a look at a very basic stack implementation, only implementing a push and pop method.
stack.c:
#include <stdio.h>
#define MAXSIZE 10
struct stack
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;
void push(int num)
{
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}
/* Function to delete an element from the stack */
int pop()
{
int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);
}
else
{
num = s.stk[s.top];
printf ("popped element is = %d\n", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);
}
Some examples of basic tests are below:
Testing push and pop:
push(1);
push(2);
int popped_element = pop();
munit_assert(popped_element == 2);
// you could also do:
// munit_assert_int(popped_element, ==, 2);
This should yield the output:
Running test suite with seed 0x0115c9cb...mimir/
-----------
popped element is = 2
-----------
[ OK ] [ 0.00001871 / 0.00001817 CPU ]
1 of 1 (100%) tests successful, 0 (0%) test skipped.
Notice that the contents printed to stdout are preserved in the output of the unit test, in between the lines of hyphens. If you allow students to see their output, this will be visible to them!