Before we start setting up Google Test, let's download Google C++ Testing Framework from the GitHub link here: https://github.com/google/googletest. Click on the Clone or download button and then Download ZIP:
Once you have all the required files, unzip the files to a directory on your PC and follow these steps to create a test project:
- Create a new project by going to File | New File or Project.
- Select Auto Test Project under the Other Project category.
- In the Project and Test Information dialog, pick Google Test for the Test framework option.
- After that, fill in the Test suite name and Test case name fields.
- Check the Enable C++ 11 checkbox if you want to support C++ 11 features in the test.
- As for the Google test repository field, select the directory where you unzipped the file you just downloaded from GitHub—for example, C:\googletest-master.
- Select your Build system. Leave it as qmake if you are not sure of what to do. You only need to change this option if you are using certain other build systems such as CMake or Qbs.
- Press Next and complete the rest of the process.
Once the project has been created, you will see that several things have been set up for you by the project wizard we just walked through. If you open up gtest_dependency.pri, you can see that the settings for INCLUDEPATH, SOURCES, and so on have all been set for you. The actual source file that contains the test functions is located at tst_testscene.h, which looks something like this:
#ifndef TST_TESTCASE_H
#define TST_TESTCASE_H
#include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>
using namespace testing;
TEST(TestSuite, TestCase)
{
EXPECT_EQ(1, 1);
ASSERT_THAT(0, Eq(0));
}
#endif // TST_TESTCASE_H
Similar to Qt Test, Google Test also uses macros such as EXPECT_EQ and ASSERT_THAT to do the test. This is what they do:
- EXPECT_EQ: A non-fatal assertion that does simple true/false condition testing, similar to QCOMPARE. Any macros that start with EXPECT_ will not terminate the auto test when detecting a failure. The test will carry on after displaying the failure on the terminal.
- ASSERT_THAT: This macro allows a much more complicated test to be done. The first input is the value you want to test with this assertion, while the second input is the condition of the test. In the preceding example, the assertion tests for value 0 and the condition is equal to 0, which can be represented by Eq(0). You can use this to compare much more complicated variables, such as maps or vectors—for example, ASSERT_THAT(v, ElementsAre(5, 10, 15));. The ASSERT_ keyword tells us that this is a fatal assertion, which means that the test will be stopped immediately when detecting a failure.
If you build and run the project now, you should see a similar result to this:
Now, let's see how Boost tests work.