Hi,
I was told by my boss to write unit tests for the little c file (foo.c) I wrote. I read a lot about the background of unit testing online, like testing only one function and making tests fully automated, but I did not find any tutorial about how to implement an actual unit test. I tried the following approach, but failed.
/*foo.c*/
#include foo.h
#if UNIT_TESTING
#define main example_main
#endif
int foo1(...){...}
int foo2(...){...}
int main(int argc,char **argv) {
foo1(...);
foo2(...);
}
/*test_foo.c*/
#include "foo.h"
void main(int argc,char **argv) {
int i = example_main(argc,argv);
return;
}
/*foo.h*/
int example_main(int argc,char **argv);
As cmd I use:
gcc -Wall -pedantic foo.c test_foo.c -DUNIT_TEST=1 -o test_foo.out
I get following erros:
test_foo.c: warning: return type of ‘main’ is not ‘int’
test_foo.c: In function ‘main’:
test_foo.c warning: unused variable ‘i’
/tmp/ccbnW95J.o: In function `main':
test_foo.c: multiple definition of `main'
/tmp/ccIeuSor.o:foo.c:(.text+0x538b): first defined here
/tmp/ccbnW95J.o: In function `main':
test_foo.c:(.text+0x17): undefined reference to `example_main'
collect2: ld returned 1 exit status
What did I do wrong? Or would you recommend another approach to unit testing.
Thank you!
[update] corrected typos in my code and posted the updated error messages
[update/clarification]
I am supposed to use cmockery so I tried the 'calculator.c' example from the cmockery website, but could not get it to run. In my reading I got the impression that unit tests don't rely on a framework. So I wanted to start with a very simple example to play around. The "#if UNIT_TESTING #define main example_main"
came from the cmockry 'manual'.