For this week, I wanted to look at how different languages handle test cases, and I’ll continue with one I’m not the most familiar with, C! I’ve worked in small amount of C in classes at Worcester State, but have little experience outside of that. I feel like this is a good topic to discuss as knowing how other programming languages handle unit testing would be a great way to expand my knowledge when it comes to furthering my understanding of it within Java.
If you haven’t already read my other blog post on Python testing, feel free to read it right here!
It seems like unit testing in C is a lot more barebones compared to Java, which in my experience utilizing C, makes sense for the language. A lot of features primarily used in Java, like object-oriented structures aren’t available in C (to my understanding, could totally be wrong).
For one major aspect, there seems to be only one assertion command in C, just simply “assert”. Theres no assertTrue, assertFalse, assertThrows, or assertEquals, just simply “assert”. And from the example given below:
#include <assert.h>
// In my_sum.c
int my_sum(int a, int b) {
return a + b;
}
// In test_my_sum.c
int main(int argc, char *argv[]) {
assert(2 == my_sum(1, 1));
assert(-2 == my_sum(-1, -1));
assert(0 == my_sum(0, 0));
// ...
return(0);
}
It seems the “assert” function comes from the <assert.h> library, much like the JUnit librarys used in Java. But more importantly, it seems that “assert” is the equivalent of “assertEquals”.
It also seems like Unit Testing in C is best implemented with tools outside of a compiler for C. The ones mentioned in the article in specific were CppUTest, Unity, and Google Test. For the rest of the article, the use examples using CppUTest. It was interesting to hear one of the options being called Unity, which is the name of a game engine, which, while not written in C, is written in a mixture of C# and C++, which are both offshoots of C. Makes me wonder how testing in a gaming engine works, perhaps it’s something to look at in a future blog post, hint hint, wink wink.
CppUTest seems to implement the same SetUp() and Teardown() functions that JUnit can employ, which is really good, as these methods are important for testing multiple methods. It also seems to have more then just an Equals assertion, even though the example used is another equals example.
This gets me more interested in C, as I have been told understanding C allows you to understand other languages much more clearly. Perhaps I’ll take a deeper dive some day, who knows! Until next time, my readers~!
From the blog CS@Worcester – You're Telling Me A Shrimp Wrote This Code?! by tempurashrimple and used with permission of the author. All other rights reserved by the author.