Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Unit testing for c code in simple way #47

@ARibecaJob

Description

@ARibecaJob

Hi,

I want to share you some info on how we can add some checking (unit testing) to existing code.
There are many unit testing libraries floating around the web but I think for our needs we can use a C features to mimic unit testing usage: macros.

In C language, we can have parts of code that can be enabled by defining a symbol (keyword):

#ifdef ENABLE_TEST
puts("some test enabled!");
#endif

if the compiler during compilation will find ENABLE_TEST defined, the code inside the block will be compiled.
Let's make a working example:

#include <stdio.h>

int main(void)
{
	int a = 5;
	printf("the value of a is %d\n", a);
	
#ifdef ENABLE_TEST
	puts("test enabled!");
	printf("a is %s than 10\n", (a < 10) ? "<" : ">=");
	puts("end of test!");	
#endif

	return 0;
}

if we compile it with gcc:

gcc main.c && ./a.out

we have as output:

the value of a is 5

but if we compile it declaring ENABLE_TEST definition using -D parameter

gcc -DENABLE_TEST main.c && ./a.out

we'll have

the value of a is 5
test enabled!
a is < than 10
end of test!

As you can see, we can easily enable or disable this kind of checking.
Let's do a better example:

#include <stdio.h>

#ifdef ENABLE_TEST
#define str__(a) #a
#define STR(a) str__(a)
#define TEST(condition) \
		if (!(condition)) printf("condition '%s' fails at row %u in function %s inside file %s\n", \
		STR(condition), __LINE__, __FUNCTION__, __FILE__)
#else
#define TEST(unused)
#endif

int main(void)
{
	int a = 5;
	printf("the value of a is %d\n", a);
	
	// it will fail, condition must be true!
	TEST(a > 10);
	// nothing happens
	TEST(a < 7);

	return 0;
}

In this example the macro TEST will evaluate only if ENABLE_TEST is defined, otherwise nothing happens.
Again if we compile and run it

gcc -DENABLE_TEST main.c && ./a.out

we have

the value of a is 5
condition 'a > 10' fails at line 19 in function main inside main.c file

We can eventually adopt this to encapsulated a unit testing library too:

// please note: simplified example
#ifdef ENABLE_TEST
#include "unit_test_files.c"
#define TEST(condition) unit_test_func(condition)
#else
#define TEST(unused)
#endif

Any ideas ?

Otherwise this seems like a good candidate for unit testing: https://github.com/sheredom/utest.h

Metadata

Metadata

Assignees

No one assigned

    Labels

    Priority:LowLow Priority Issue or PR

    Type

    No type

    Projects

    Status

    Priority:Low

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions