Cmake Gtest Example

/ Comments off

Today, let’s talk about the cmake test. However, we are still talking about C + + testing. Cmake provides us with perfect testing support, for example, it has a special module ctest. Cmake native test support The cmake native support test is very simple, with only two functions: enabletesting addtest(NAME COMMAND. CONFIGURATIONS. CMake and CTest with Google C Testing Framework. CMake makes it very easy to add other projects that use CMake to the build as a dependency. Google’s C Testing Framework provides a CMakeLists.txt, so all you need to do in order to add gtest to your project is point your CMakeLists.txt to the gtest folder. Mine’s in the ‘lib’ folder. Many of these examples include standard CMake modules. Building a C/C unit test (gtest) We use Google Test (gtest) for unit testing of C/C code. Example # the usual boilerplate setup cmakeminimumrequired(2.8) project(mytestproject LANGUAGES CXX) # tell CMake to use CTest extension enabletesting # create an executable, which instantiates a runner from # GoogleTest, Boost.Test, QtTest or whatever framework you use addexecutable(mytest testmain.cpp) # depending on the framework, you need to link to it targetlinklibraries(mytest gtest. C project setup with CMake & unit tests (google test) - Raymii.org. Table of Contents Install cmake & googletest Folder structure CMakeLists.txt Main folder CMakeLists.txt src folder CMakeLists.txt: tst folder CMakeLists.txt: Add some (example) source code and tests Source Code Test code Compile all the things Run all the things This guide will show you how to setup.

Skip to main content

C++ project setup with CMake & unit tests (google test)

Published: 01-10-2019 Last update: 06-11-2019 Author: Remy van Elst Text only version of this article


❗ This post is over one year old. It may no longer be up to date. Opinions may have changed.

Table of Contents

Example
  • CMakeLists.txt
  • Add some (example) source code and tests

This guide will show you how to setup a new C++ project with CMake and unit testsvia Google's test framework. With this setup you can get started right away with test-driven-development in C++. It is also simple enough to look and figureout how to add gtest to your existing project and start doing TDD on your legacy (existing) codebase.

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.
You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $100 credit for 60 days.

The picture below shows the end result, a running unit test:

There are a million different ways to 'do' C++ projects, but using CMake andthe google testing framework has my preference. That's not to say that using a Makefile or Boost Unit Test is bad, use whatever suits your needs. This guide however will focus on just CMake and gtest.

It assumes a system running Ubuntu (18.04). It also works on Windows with mingw,but I haven't tested in with MSVC.

My preferred code editor is CLion from Jetbrains, which has most of this built in. This guide however focusses on the manual / command line way since CLion isnonfree (and paid) software.

The process is not that complicated:

  • Install software (cmake and googletest)
  • Create folder structure
  • Create the CMakeLists.txt files
  • Create some sample code and sample tests
  • Compile everything
  • Run the tests

Install cmake & googletest

I assume you already have your compiler installed and working. Installing cmakecan be done with the package manager on Ubuntu:

On Windows, you can use MinGW or cygwin to install your development tools including CMake. Clion offers a nice GUI for that.

Googletest is available as a git repository which you can clone and then copyinto your project. You could go all fancy with CMake scripts to download itif it's not already in your project, but since you can clone once and copy later on I choose not to automate it. Clone the repository:

gtest comes with a CMakeLists.txt so integrating it in your project is easy.

Folder structure

Create your C++ project folder. I like to keep the following structure for simpleprojects:

Here is a oneliner to create the folders:

Copy the googletest repository folder your cloned earlier into the lib/ folder.

If you have multiple components you can create extra sub folders, but that doesrequire tweaking the CMakeLists.txt files to work with multiple libraries.

Most of my personal projects are simple enough to fit into one folder as above.

In the tst folder the unit tests reside. I try to keep the tests limited to the same function in seperate files. In the above example I have Formula.h and Formula.cpp, which house the example Formula class. All unit tests relatedto this class thus should reside in Formula-test.cpp.

CMakeLists.txt

The file CMakeLists.txt contains a set of directives and instructionsdescribing the project's source files and targets (executable, library, orboth). This can get quite complex quite fast, CMake has many options. I try tokeep it simple in this guide.

I'm using a non-recommended way to include files. For simple projects with a few files you should use the following:

I'm using this:

That is a recursive search to include all *.cpp and *.h in the folder. Inmy IDE I have auto-reload enabled, that way I can't forget to add a fileto CMakeLists.txt every time. For proper administration you should not use thissince it just includes everything, could have unwanted side-effects.

Update 2019-11-07: If you want Boost in this setup, read this article from me.

Each subdirectory in our case also needs a CMakeLists.txt file.

Main folder CMakeLists.txt

The name of the project is ExampleProject, that variable is used in other files.The rest of the file just includes the different subfolders. If you omit the include_directories(src), your tests will not be able to find the header files.

src folder CMakeLists.txt:

The name of the compiled program will be ExampleProject_run, which is whatwe defined in add_executable. The add_library is used to include the codein the unit tests.

tst folder CMakeLists.txt:

This list used the src defined library and adds the tests as a target. The compiled executable file is named ExampleProject_tst.

Add some (example) source code and tests

At this point you start developing. But since this is a example setup, I'll adda simple class file to show you how to do the unit tests.

Source Code

Copy the below code into your project:

src/main.cpp:

src/Formula.h:

src/Formula.cpp:

This function returns the given int multiplied by 2.

Test code

The following code is to setup the unit tests.

tst/main.cpp:

This file will run all the tests and since we recursively included everythingwith CMake, it will effectively run all tests in all files in this folder.

tst/Formula-test.cpp:

The Google Test Primer is a great starting point to learn more on the specificsof the testing framework.

Compile all the things

Now that we have sourcecode and testcode in place we can compile everything (both the binary and the tests).

Do note that you should do this in the build folder. If you do it in the main folder it will work, but it will litter up the directory.

Output:

There are now a bunch of files and folders in the build folder, most important,the Makefile. You can now compile the project:

Output:

You now have two executable files, as defined in the CMakeLists.txt:

Run all the things

If all went well, the code should run:

Output:

The tests as well:

Output:

A quick one-liner to compile and run the tests. You can run this wheneveryou want to re-run the tests (after changing code for example):

Output:

As you can see I changed a unit test so that it failed.

Tags: boost, c++, cmake, cpp, development, googletest, linux, software, testing, ttd, tutorials

Google Test and Google Mock are a pair of unit testing tools developed by Google.

Learn about the framework specifics in the Google Test section of our Unit Testing Tutorial.

Adding Google Test to your project

  1. Download Google Test from the official repository and extract the contents of googletest-master into an empty folder in your project (for example, Google_tests/lib ).

    Alternatively, clone Google Test as a git submodule or use CMake to download it (instructions below will not be applicable in the latter case).

  2. Create a CMakeLists.txt file inside the Google_tests folder: right-click it in the project tree and select New CMakeLists.txt.

    Customize the following lines and add them into your script:

    # 'Google_test' is the subproject name project(Google_tests) # 'lib' is the folder with Google Test sources add_subdirectory(lib) include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR}) # 'Google_Tests_run' is the target name # 'test1.cpp tests2.cpp' are source files with tests add_executable(Google_Tests_run test1.cpp tests2.cpp) target_link_libraries(Google_Tests_run gtest gtest_main)
  3. In your rootCMakeLists.txt script, add the add_subdirectory(Google_tests) command to the end, then reload the project.

  4. When writing tests, make sure to add #include 'gtest/gtest.h' at the beginning of every .cpp file with your tests code.

Take a look at this example in Unit Testing Tutorial.

Generate menu for Google Test

In the files with gtest included, you can generate code for tests and test fixtures using the Generate menu Alt+Insert.

When called from a fixture, this menu additionally includes SetUp Method and TearDown Method:

Google Test run/debug configuration

Although Google Test provides the main() entry, and you can run tests as regular applications, we recommend using the dedicated Google Test run/debug configuration. It includes test-related settings and let you benefit from the built-in test runner, which is unavailable if you run tests as regular programs.

CLion automatically creates a Google Test configuration for every CMake target linked with gtest or gmock.

  1. To create a Google Test configuration, go to Run Edit Configurations, click and select Google Test from the list of templates.

  2. Specify the test or suite to be included in the configuration, or provide a pattern for filtering test names. Auto-completion is available in the fields to help you quickly fill them up:

    YOU MAY NOT ASSIGN OR OTHERWISE DISPOSE OF, MODIFY, ADAPT, TRANSLATE, RENT, LEASE, LOAN, RESELL, DISTRIBUTE, NETWORK, OR CREATE OR HAVE CREATED DERIVATIVE WORKS BASED UPON THE MANUAL OR ANY PART THEREOF. Urc complete control program download LIMITED WARRANTY AND DISCLAIMERTO THE MAXIMUM EXTENT PERMITTED UNDER APPLICABLE LAW, THE MANUAL IS PROVIDED ON AN 'AS IS' BASIS, WITHOUT WARRANTY OF ANY KIND, AND NIKON, ITS EMPLOYEES, DISTRIBUTORS, DEALERS AND AGENTS SPECIFICALLY DISCLAIM ANY WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. YOU MAY NOT ALTER OR REMOVE ANY COPYRIGHT, TRADEMARK OR OTHER PROTECTIVE NOTICES CONTAINED IN THE MANUAL.

    Set wildcards to specify test patterns, for example:

    In other fields of the configuration settings, you can set environment variables and command line options. For example, use Program arguments field to pass the --gtest_repeat flag and run a Google test multiple times:

    The output will look as follows:

    Repeating all tests (iteration 1) ..Repeating all tests (iteration 2) ..Repeating all tests (iteration 3) ..
  3. Save the configuration, and it's ready for Run or Debug.

Instead of editing a single configuration, you can modify the Google Test template itself. In this case, the settings you specify will apply as defaults to all new configurations of this type.

Cmake Gtest Example Pdf

Running tests

In CLion, there are several ways to start a run/debug session for tests, one of which is using special gutter icons. These icons help quickly run or debug a single test or a whole suite/fixture:

Gutter icons also show test results (when already available): success or failure .

When you run a test/suite/fixture using gutter icons, CLion creates a temporary Google Test configuration, which is greyed out in the configurations list. To save a temporary configuration, select it in the Edit Configurations dialog and press :

Exploring results

When you run tests, the results (and the process) are shown in the test runner window. This window includes:

  • progress bar with the percentage of tests executed so far,

  • tree view of all the running tests with their status and duration,

  • tests' output stream,

  • toolbar with the options to rerun failed tests, export or open previous results saved automatically , sort the tests alphabetically to easily find a particular test, or sort them by duration to understand which test ran longer than others.

Test tree shows all the tests while they are being executed one by one. For parameterized tests, you will see the parameters in the tree as well. Also, the tree includes disabled tests (those with the DISABLED prefix in their names) and marks them as skipped with the corresponding icon.

Skipping tests at runtime

Cmake Gtest Example

You can configure some tests to be skipped based on a condition evaluated at runtime. For this, use the GTEST_SKIP() macro.

Cmake Gtest Example Of Database

Google Test supports this feature starting from the version 1.10.0, so make sure to update the framework's sources in your project.

Add the conditional statement and the GTEST_SKIP() macro to the test you want to skip:

TEST(Foo, Bar) { //.. if (condition) GTEST_SKIP_('message'); // or GTEST_SKIP() with no message //.. }

Cmake Gtest Example Free

Use the Show ignored icon to view/hide skipped tests in the Test Runner tree: