Usually, then I code I write test just to be sure code works as expected. C is not nicest (easy to understand) language to work with, especially when you start to learn to code. Because of time pressure on projects I had I didn't want invest time to check available C Testing libraries. So I created my own simple "C BabyTest" library.
Test.assertTrue(bool actual, char * message):bool
: Test ifactual
is reallytrue
.Test.assertFalse(bool actual, char * message):bool
: Test ifactual
isfalse
.Test.assertEqual_String(char * expected, char * actual, char * message):bool
: Test ifactual
string are the same asexpected
string.Test.assertEqual_Int(int expected, int actual, char * message):bool
: Test ifactual
integer are the same asexpected
integer.
Note each test function returns true if a test is passed.
Is always good practice to separate test code from main programs code. But for this example for simplicity reasons is not the case
#include <stdio.h>
#include <stdbool.h> // to suport booleans
#include "test.h" // this library
// Note: this include shoud point to location where library is.
// In my case it is in the same folder.
#define MY_AGE 30 // constant to hold my age
// function you want to test
bool imOlder(int yourAge){
// some creazy logic you not sure about
return MY_AGE < yourAge;
}
int bobAge = 20; // Bob age
// you know what you older then Bob.
bool shouldBe_True = imOlder(bobAge);
// test if function implementation is correct
Test.assertTrue(shouldBe_True, "I'm older then Bob");
To run on Windows + VisualStudio hit run. To run (on Linx):
# go to yours tests files folder
# compile all ".c" files to "myTest.out" file
gcc ./*.c -o ./myTest.out
# if no compile errors run it
./myTest.out
So then you run it result is:
I'm older then Bob: true - FAIL
So you know what your implementation is wrong. Lets fix it. Change function to:
bool imOlder(int yourAge){
// some creazy logic you not sure about
return MY_AGE > yourAge; // changed "<" to ">"
}
Then you run result now:
I'm older then Bob: true - PASS
And know you know what function works as expected.