Finally, we will learn how to create Boost tests. As the name implies, Boost tests require a set of third-party C++ libraries called Boost. You can download it from Boost's official website at https://www.boost.org. Once you have downloaded the ZIP file, extract it somewhere on your PC as we will need it later. When you're done, check out 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 Boost Test for the Test framework option.
- After that, fill in the Test suite name and Test case name fields.
- Then, go to the directory of Boost where you unzipped the download and copy the directory path to the Boost include dir (optional) field—for example, C:\boost_1_71_0.
- 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.
When the project has been created, open up main.cpp:
#define BOOST_TEST_MODULE TestSuite
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE( testCase )
{
BOOST_TEST( true /* test assertion */ );
}
We can see the resemblance between the different unit test suites. Boost also uses macros, though they start with BOOST_, and it works pretty similar to Qt Test and Google Test too. The most common macro that you will use is BOOST_TEST, which works for most of the test cases. For instance, we can change the BOOST_AUTO_TEST_CASE function as follows:
BOOST_AUTO_TEST_CASE( testCase )
{
int a = 5;
int b = 6;
BOOST_TEST(a != b - 1);
}
As you can see from the preceding code, we've intentionally made it a fail test, just to see what the outcome from the application is. Let's build and run the program now. You should see something similar to the following screenshot:
Other than that, Boost also supports assertions with different severity levels:
- BOOST_TEST_WARN: Lowest severity level. This would not even raise the error count if the test failed to perform. The auto test will continue to proceed to the next test function if the current test has failed.
- BOOST_TEST_CHECK: Medium severity level. This is actually the same as BOOST_TEST, which we used in the previous example. If this test failed to perform, it would increase the error count but would not stop the auto test from continuing.
- BOOST_TEST_REQUIRE: Highest severity level. This assertion would both increase the error count and stop the auto test when the test returns a failed result.
In this section, we have learned how we can set up effective auto tests using various types of unit test suites.