Unit Test How? main( )
This is part of an ongoing series of articles about using Unity to Unit Test C applications, often for Embedded Applications. If you're looking for other tips, be sure to check out the others here.
Today we're going to talk about testing that ubiquitous function in C: main. If our tests declare a main function of their own, how can we make them call our release code's main function?
It's a simple little hack, actually. We're going to use our old friend, the TEST define. If we always build our tests with TEST defined, then we can count on this to give us a little help.
In main.c, we're going to add a few lines at the top, like so:
#ifndef TEST
#define MAIN main
#else
#define MAIN testable_main
#endif
Now, instead of declaring our main function as main, we're going to use our macro. Something like this:
int MAIN(int argc, char* argv[])
{
//Stuff worth testing...
}
When we write our test, we can now call testable_main in place of main, and test as usual. Being the main function, it's likely going to be coordinating many other modules... so in all likelihood, we'll be wanting to dust off our CMock skills and get down to work.
Happy Coding!