Skip to content

Instantly share code, notes, and snippets.

@aprell
Created November 20, 2011 17:54
Show Gist options
  • Save aprell/1380577 to your computer and use it in GitHub Desktop.
Save aprell/1380577 to your computer and use it in GitHub Desktop.
Simple unit testing for C
#include <stdio.h>
#include <stdlib.h>
#include "module.h"
#include "utest.h"
extern UTEST(module);
UTEST_MAIN()
{
utest_module();
}
int main(void)
{
utest();
return 0;
}
CC = gcc
CPPFLAGS += -D_GNU_SOURCE
CFLAGS += -O0 -g -Wall -Wextra
SRCS = driver.c module.c
OBJS = $(SRCS:.c=.o)
all: utest
utest: $(OBJS)
$(CC) -o $@ $^ $(LDFLAGS) $(IMPORTS)
clean:
rm -f utest $(OBJS)
driver.o: module.h utest.h
module.o: module.h utest.h
.PHONY: all clean
#include "module.h"
#include "utest.h"
int A(int a, int b)
{
return a + b;
}
int B(int a, int b)
{
return a - b;
}
UTEST(module)
{
check_equal(A(1, 2), 3);
check_equal(A(-2, 6), 4);
check_equal(A(-4, -1), -5);
check_equal(A(9, 0), 8 + 1);
check_equal(B(4, 5), -1);
check_equal(B(5, A(3, 4)), -5);
check_equal(B(A(2, 1), A(1, 2)), 0);
}
#ifndef MODULE_H
#define MODULE_H
int A(int a, int b);
int B(int a, int b);
#endif // MODULE_H
#ifndef UTEST_H
#define UTEST_H
#include <stdio.h>
#include <stdlib.h>
#define check_equal(a, b) \
{ \
utest_count++; \
if ((a) != (b)) { \
fprintf(stderr, "Test %3u failed: %s != %s\n", utest_count, #a, #b); \
utest_count_failed++; \
} \
}
#define UTEST(name) \
void utest_##name(void)
#define UTEST_MAIN() \
unsigned int utest_count; \
unsigned int utest_count_failed; \
UTEST(main)
#define utest_init() \
{ \
utest_count = utest_count_failed = 0; \
}
#define utest_exit() \
{ \
fprintf(stderr, "%u of %u tests completed successfully\n",\
utest_count - utest_count_failed, utest_count); \
if (utest_count_failed) \
abort(); \
}
#define utest() \
{ \
utest_init(); \
utest_main(); \
utest_exit(); \
}
extern unsigned int utest_count;
extern unsigned int utest_count_failed;
#endif // UTEST_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment