This post is a quick introduction to Google Test and how to use it to test your C++ code. Google Test is a unit testing framework that is easy to use and creates meaningful tests with intuitive output.
On Debian based systems, you will want to install the following packages:
libgtest-dev includes the headers and sources, but not the compiled libraries. Follow the instructions below to compile and install the libraries1:
cd /tmp mkdir build cd build cmake -DCMAKE_BUILD_TYPE=RELEASE /usr/src/gtest/ make sudo mv libgtest* /usr/lib/
You could also use
checkinstall to create a deb package containing the library files.
To get started, you will need to:
- Include the Google Test headers
- Write a
- Initiate the unit tests from
Tests are composed of various
EXPECT_* statements to ensure that functions return expected values, etc. For a full description of the various types of tests that can be written using Google Test, refer to the documents below:
1 2 3 4 5 6 7 8 9 10 11 12
One thing to remember with the
EXPECT_* statements is that the first argument is the hardcoded expected value (ie: the “truth”), and the
second parameter is the variable or function call to be tested.
To compile, you need to link against both the compiled gtest library as well as pthread:
g++ -g -O0 main.cpp -lgtest -pthread
The output will look something like this:
1 2 3 4 5 6 7 8 9 10
Google Test is a great way to ensure that your code is working properly. I often use Google Test with a relaxed form of Test Driven Development2.