C++ unit tests with googletest
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.
Setup environment
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
Create a symbolic link to google testing framework directory
I have google test located in my home dir dev-tools/gtest-1.7.0, so:
Write sample functions that will be tested
cpp-googletest-cmake/src/lib1.hpp:
cpp-googletest-cmake/src/lib1.cpp:
Create build scripts
googletest-cmake/src/CMakeLists.txt:
CMake does the main build process, but we also use a helper Makefile that runs cmake and the compiled tests executable.
googletes-cmake/src/Makefile:
Create test suite
googletes-cmake/test/lib1_test.cpp:
|
#include <gtest/gtest.h>
|
|
|
|
#include "lib1.hpp"
|
|
|
|
|
|
TEST(lib1, sum)
|
|
{
|
|
int s = sum(10, 15);
|
|
ASSERT_TRUE(s == 25);
|
|
}
|
|
|
|
TEST(lib1, mul)
|
|
{
|
|
int m = mul(10, 15);
|
|
ASSERT_TRUE(m == 150);
|
|
}
|
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.
Run tests
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.
Comments