Test your C++ code with Catch

I recently came upon the need to test some code, but I didn’t want to bother with doing manual testing. Hence, unit testing. It’s magic for real, when you have a nice system to do it. This is where Catch comes in handy. Catch is a very powerful testing tool for C++, that is header only. Now that is magic. No external library. And it’s only one header file. Even better. No? Yes.

Using Catch

Catch is easy, simple, and efficient. For real. I recently decided to test it on my small config class I made for my general utility library. Writing a test case is as easy as this:

Catch TestCase
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
TEST_CASE("RSM::Config", "[config]") {

RSM::Config config;

SECTION("Creating a config file from scratch") {
config.set("StringKey", "StringValue");

REQUIRE(config.hasConfig("StringKey") == true);

REQUIRE_NOTHROW(config.save("config.txt"));
}

SECTION("Loading a config file") {
REQUIRE_NOTHROW(config.load("config.txt"));

REQUIRE(config.hasConfig("StringKey") == true);

REQUIRE(config.get("StringKey") == "StringValue");
}
}

That’s it. This test the creation of a config file, and the loading of said config file. Compile, run, done. How hard can it be?

Onward to…

What comes out of this is the simplicity that I can make unit test for pretty much anything now, for all my projects. I intend to try myself at TDD eventually. I believe Catch is going to help me for that.