Unit Tests in C
- Pablo Narvaja

- Jul 13, 2020
- 2 min read
Hi! I've been very busy with a new job and the engine, now getting a very strong base, but here I am again with you folks.
Background
I am doing a core library with arrays, dynamic arrays, queues, string in C and also adding thread support! Anyway, I realized that i needed to do little tests on what I was developing and using the engine "Class" to run them was very anoying and seemed very wrong so I started to look for a framework to do unit test in C.
Choosing the Framework
I looked for some libraries like Cunits and started to see that some recomend it but some say it lacks some features and things like that and I said to myself "how difficult can it be to do a little framework myself?" And you know me I dont want to use any library in my engine so I did my own tool (and some others that I'll be posting soon). It is very very rudimentary but it does it job very well.
Developing the tool
Given that I've been doing some work to abstract the thread in the engine it came to my mind that i could run every test in a different thread and then look for the exit code and determine if it succeded or not. I only used win32 API so test wont run on other platforms but someday they will.
The flowchart of the tool look like this:

the "Spawn all thread for every test"(yellow) box is marked because i want to talk about it. Some may say that if the project scale too much the amount of threads to spawn will be overkill and will not be possible to run all tests (maybe depends on the OS) This is provisory it works really well so far with 2 tests, of course, and I look forward to refactor if needed.
Another thing to have in mind is that this tool compile all the engine again with out the main entry so it can use all the code. I dont know if this is how all test frameworks works in C and I did not think about it that much but if there is a way to improve this I would love to hear about.
Example of use
1. Define the test in a header file. In order to make the function firm uniform and easy to replicate I did a macro.

Here we can see to the macros expand to.

2. Then in the main file where we use the test tool we import the header file and add the test to the tool like this.

To add the test in a "automated" way I created the macro LT_ADD_TEST that expands to this.

3. Running the tool looks like this.

As you see the first test failed as it finish with an error code different than 0. This is intended behaviour so should test for the corresponding error code.
4. To do this we pass the expected exit code to test for (ErrorCodes.h is part of the engine not the tool):

And then the run looks like this:

Conclusion
As we can see the tool is very simple but it gets the work done. As a first 1 hour iteration I am very proud of it. I would love to hear about any improvement for this!
That's all for this post, folks. Bye!

Comments