...
To present an example of using GoogleTest, we first need to create a project in C++. In the project directory named Calculator, before starting to write codes, it is necessary to prepare its structure. It will need two subdirectories named src and tst - one for the source codes and one for the tests codes. At this point, these folders can be filled with empty files with appropriate names for sources: operation.cpp; operations.h, and for tests: run_tests.cpp; test_operations.cpp. However, each of these files can be created later during development.
Tests
Tests supervisor file
To start writing tests, it is needed to create run_tests.cpp and test_operations.cpp (if not done previously). In order to force GoogleTest to automatically search for test files, the file run_tests.cpp comes in handy. Typically, a code inside this file will be universal for all kinds of projects:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
#include "gtest/gtest.h" int main(int argc, char **argv){ ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } |
Tests suites file
However, the actual test cases are placed in a separate file, the name of which corresponds to the name of the file that stores the code to be tested. It is good practice to name the test file using the name of the source file being tested with the keyword test
appended as a prefix or suffix separated by the underscore "_" or the dash "-". The goal of this tutorial is to test the division function stored in operations.cpp, although it does not exist at this point, it is predicted that it will be. Therefore, the file with the test code is named test_operations.cpp, and should look like this:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
#include <gtest/gtest.h> #include "operations.h" TEST(DivideOperation, PositiveInput) { // Integer arguments ASSERT_EQ(divide(10, 5), 2); ASSERT_FLOAT_EQ(divide(5, 10), 0.5); // Floating-point arguments ASSERT_FLOAT_EQ(divide(10.0f, 5.0f), 2.0f); ASSERT_FLOAT_EQ(divide(5.0f, 10.0f), 0.5f); } TEST(DivideOperation, NegitiveInput) { // Integer arguments ASSERT_EQ(divide(-10, -5), 2); ASSERT_FLOAT_EQ(divide(-5, -10), 0.5); // Floating-point arguments ASSERT_FLOAT_EQ(divide(-10.0f, -5.0f), 2.0f); ASSERT_FLOAT_EQ(divide(-5.0f, -10.0f), 0.5f); } TEST(DivideOperation, ZerioInput) { // Integer arguments EXPECT_THROW(divide(10, 0), std::overflow_error); // Floating-point arguments EXPECT_THROW(divide(10.0f, 0.0f), std::overflow_error); } |
...