Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Table of Contents
maxLevel3
exclude.*:

Create The Calculator project

sources:

To present an example of using GoogleTest, we first need to create a project in C++. In the project directory named Calculator, we will create the C++ source and header files in the appropriate directories. For the tutorial, we create operations.cpp in the src directory, which contains a simple divide function and the operation.h header file. However, C++ is a statically typed language and therefore we need to supply multiple definitions of a division function according to the type of its input arguments. The output of a function should always be floating point, but for the purposes of this tutorial, we predict that the input arguments can be both integers and floating point numbers. Therefore, two definitions have been introduced for each of these types. The header file should look like this:

...

The presented function has a mechanism for verifying whether the divisor (denominator) is equal to zero or is close to zero in the case of a floating-point number. In case the condition evaluates to True, an exception is thrown. To implement the exception, include the <stdexcept> library. Under normal circumstances, the output value is computed and returned as floating point in both cases.

tests:

We also need to create a folder for our tests. In this tutorial, this folder is called tst. To start writing tests, we will create run_tests.cpp and test_operations.cpp. We want GoogleTest to search for test files automatically, and we do this thanks to the code stored in the run_tests.cpp source file. Typically, this code will be universal for all kinds of projects:

...

Code Block
languagebash
titleCalculator/ $: tree
.
├── src
│   ├── operations.cpp
│   └── operations.h
└── tst
    ├── run_tests.cpp
    └── test_operations.cpp


Build the project  - CMake

After the source and test code are ready, the project can be built and compiled. At the top of the project's folder structure, add CMakeLists.txt. The contents of the file are listed below:

...