Google Test is one of the available Frameworks to create unit test for C++. In this example I will use CMake to configure the project and build. Furthermore, for the dependency manager I will use the new and shiny conan.
Before starting, why use a dependency manager such as conan or software to configure and build such as CMake? Because these technologies are widely use it in real projects.
All the code and configuration files used in this post are available in this repo in GitHub. # Step 1 Install conan, configure project and gather dependencies First of all we need to have install conan from pip2 doing:
Now with conan installed we do not have to worry about installing Google Test in our system.
Next step will be preparing the conanfile.txt to gather de dependencies:
Once we have conan ready we only need to run it to download the dependency and configure them to have them ready for CMake: This will output something similar to:
Step 2 configuring CMake
The configuration will be done in the CMakeLists.txt file:
Step 3 code and unit test
The code will be held in the src folder. It will contain two files: functions.h and test.cpp.
The function(s) we want to test will be in the header file function.h:
The test(s) we want to run will be in the source file test.cpp:
Step 4 putting all together
What is left to do is actually build the project and run the test. In order to do this we need to run:
This will output something similar to:
There will be now a Makefile generated from CMake with everything ready to compile and link all the sources and dependencies together.
This will output something like:
This will generate an executable in the bin folder, and we will be able to run them with the command:
This will result with the following output:
More advanced example
These are the basics of how to use Google Test to create unit test for your application. In the website of the project there are plenty of more advanced examples.
Finally, if you want to see how is used Google Test in one of my own project you can have a look to the repository tries. For each of the three data structures (Trie, TST and Radix Tree) there are two folders: lib (where the source code of the data structure is stored) and gtest (where the unit test are stored).