How is unit testing implemented in C++?
In C++, unit testing is usually implemented using popular testing frameworks such as Google Test and Catch. These testing frameworks provide macros and functions that make it easy to write and run unit tests. Here is a simple unit test example:
#include <gtest/gtest.h>
int add(int a, int b) {
return a + b;
}
TEST(AddTest, PositiveNumbers) {
EXPECT_EQ(add(1, 2), 3);
}
TEST(AddTest, NegativeNumbers) {
EXPECT_EQ(add(-1, -2), -3);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
In the above example, we defined a simple add function and wrote two test cases using the Google Test framework to test this function. Each test case is defined using the TEST macro, and then the EXPECT_EQ macro is used within the test case to assert whether the function’s return value meets expectations. Finally, testing::InitGoogleTest is called in the main function to initialize the testing framework, and RUN_ALL_TESTS is used to run all the test cases.
In addition to Google Test and Catch, there are also other testing frameworks available for C++ unit testing, such as CppUTest and Boost.Test. Developers can choose the appropriate testing framework based on their preferences and project requirements to write unit tests.