...
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:
...
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 divide function stored in the operations.cpp file. 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); } |
Our project folder should look like this: