Starting with a simple unit test in c

My boss told me to write unit tests for the small c file (foo.c) that I wrote. I read a lot about the history of unit testing on the Internet, for example, tested only one function and fully automated tests, but I did not find a tutorial on how to implement the actual unit test. I tried the following approach, but could not.

    /*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 the 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 a different approach to unit testing.

Thank!

[update] typos fixed in my code and sent updated error messages

[/] cmockery, "calculator.c" - cmockery, . , . , . "#if UNIT_TESTING #define main example_main" cmockry.

+3
5

- , . , cunit. , , , cunit XML, - ( XSLT). , , , , .

: . , .

+8

, , C. .

+3

, ';' main() func:

int main(int argc,char **argv) {
        foo1(...);
        foo2(...)
    }
+1

, ...

/*foo.h*/
int example_main(int argc,char **argv);
+1

.

? " " main "??

One solution is to separate the main function of the software under test (SUT) from the rest of the program and not include the main function of SUT in the assembly of the test project. (Of course, this means that the original core function is no longer part of the SUT, i.e. you are not testing the original core function.)

0
source

Source: https://habr.com/ru/post/1752439/


All Articles