Closed garfr closed 3 years ago
It appears that there is no one way to unit test C code. My suggestion is to write one test function for every C code function. In terms of mocking, one can write the function declaration in the test file in order to "mock" out the original definition of the dependencies of the function being tested.
Example:
//my code.c
int my_func(int var){
return 3 + var;
}
//test_framework.h
#define SUCCESS 1
#define FAIL 0
#define ASSERT(expr) (expr)? SUCCESS:FAIL
//test_my_code.c
int test_my_func(){
int result = 0;
int neg_var = -4;
//Test negative integer less than -3
result = ASSERT(neg_var < 0);
if(result == FAIL)
goto leave
//Test positive integer
int pos_var = 4;
result = ASSERT(pos_var > 0);
if(result == FAIL)
goto leave
leave:
return result;
}
We could wrap returning into a macro like
#define ASSERT(expr) if (!(expr)) return FAIL;
With that a test could just be:
int test_my_func() {
int my_val = 0;
ASSERT(my_val == 0);
return SUCCESSS
}
I also think that it's worth creating a "unit_test.h" file containing some macros and tools to make the unit testing easier. Things like ASSERT_FALSE, ASSERT_EQ, and ASSERT_STR_EQ seem like no-brainers.
We could also write a little script that would generate a file of unit test stubs from a source file, even going as far as to have it generate a main function that calls all the unit test functions with logging and stuff.
Description
There should be a simple way to run all unit tests in a sub-directory or the entire project.
The automated test should:
This could be achieved with the introduction of a testing framework, but make sure to keep an eye open for uneeded complexity. We could also hand-roll our own testing framework to exactly suit our needs but this could be a large time sink.
Testing policy specified here: Simple HTTP Server Testing
Goals