Unit tests with googletest
Unit tests let programmer know that his software works as expected. If you i have ever done heavy development or you are planning to do so, you would definitely see the obvious advantages of unit testing your software:
you can easily check if software works on different platforms;
unit tests might replace or at least supplement the samples;
you can assert if your code still works after refactoring;
unit tests can also be used to test and track performance;
tests can be run automatically and periodically;
unit tests make you try module/library API before integrating it to the other code - this way design issues can be noticed sooner;
unit tests inspire confidence;
and many more advantages...
One of the many testing frameworks for C++ if googletest. Let's see how to write unit tests for your modules.
We'll use googletest, CMake and debian 7.3 system. Get the prerequisites:
Download the latest googletest version from here (by the time I wrote this article it was v1.7.0).
Unpack the package:
Create sample project
You can get a sample from github:
Sample project directory tree:
. |__ googletest-cmake |__ lib | |__ googletest -> ~/dev-tools/gtest-1.7.0 |__ src | |__ lib1.cpp | |__ lib1.hpp |__ test | |__ lib1_test.cpp |__ CMakeLists.txt |__ Makefile
Create directory hierarchy
Write sample functions that will be tested
Create build scripts
CMake does the main build process, but we also use a helper Makefile that runs cmake and the compiled tests executable.
Create test suite
This is the simplest form of the unit tests. It uses ASSERT_TRUE macro which checks if the specified expression is true. If it is not the test execution is terminated.
There are more convenience macros that you can use to assert expected values: https://code.google.com/p/googletest/wiki/V1_7_Primer.
Simply type make in project directory. It invokes the helper Makefile that runs CMake which builds the tests executable and then Makefile runs this executable.