测试框架 Google Test
- categories
- >
- Code
一个简单的使用 Google Test 测试框架的加减乘除示例
安装
使用包管理器
sudo emerge -av gtest
使用
简单的 C++ 代码 my_math.cpp
,实现 add()
函数
头文件my_math.h
// my_math.h
#pragma once
namespace my {
int add(int a, int b);
}
源文件my_math.cpp
// my_math.cpp
#include "my_math.h"
namespace my {
int add(int a, int b) {
return a + b;
}
}
编写单元测试test_my_math.cpp
:
// test_my_math.cpp
#include <gtest/gtest.h>
#include "my_math.h"
// 测试 add() 函数
TEST(TestMyMath, AddFunction) {
EXPECT_EQ(my::add(2, 3), 5);
EXPECT_EQ(my::add(-1, 1), 0);
EXPECT_EQ(my::add(0, 0), 0);
}
// 主函数
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
编译与运行
使用g++
g++ -o test_my_math test_my_math.cpp my_math.cpp -lgtest -lgtest_main -pthread
./test_my_math
使用 cmake
cmake_minimum_required(VERSION 3.10)
project(test_my_math)
# 启用 Google Test
find_package(GTest REQUIRED)
# 添加测试可执行文件
add_executable(test_my_math test_my_math.cpp my_math.cpp)
# 链接 Google Test 库
target_link_libraries(test_my_math GTest::GTest GTest::Main)
测试结果:
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from TestMyMath
[ RUN ] TestMyMath.AddFunction
[ OK ] TestMyMath.AddFunction (0 ms)
[----------] 1 test from TestMyMath (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
增加函数
// my_math.h
namespace my {
int sub(int a, int b);
int mul(int a, int b);
double div(double a, double b);
}
// my_math.cpp
namespace my {
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
double div(double a, double b) {
if (b == 0) {
throw std::runtime_error("Division by zero");
}
return a / b;
}
}
// 测试减法
TEST(MyMathTest, SubTest) {
EXPECT_EQ(my::sub(5, 3), 2);
EXPECT_EQ(my::sub(3, 5), -2);
EXPECT_EQ(my::sub(0, 0), 0);
}
// 测试乘法
TEST(MyMathTest, MulTest) {
EXPECT_EQ(my::mul(2, 3), 6);
EXPECT_EQ(my::mul(-2, 3), -6);
EXPECT_EQ(my::mul(0, 5), 0);
}
// 测试除法
TEST(MyMathTest, DivTest) {
EXPECT_DOUBLE_EQ(my::div(6, 2), 3.0);
EXPECT_DOUBLE_EQ(my::div(5, 2), 2.5);
}
// 测试除零
TEST(MyMathTest, DivByZeroTest) {
EXPECT_THROW(my::div(1, 0), std::runtime_error);
}
测试结果:
[==========] Running 5 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 5 tests from MyMathTest
[ RUN ] MyMathTest.AddTest
[ OK ] MyMathTest.AddTest (0 ms)
[ RUN ] MyMathTest.SubTest
[ OK ] MyMathTest.SubTest (0 ms)
[ RUN ] MyMathTest.MulTest
[ OK ] MyMathTest.MulTest (0 ms)
[ RUN ] MyMathTest.DivTest
[ OK ] MyMathTest.DivTest (0 ms)
[ RUN ] MyMathTest.DivByZeroTest
[ OK ] MyMathTest.DivByZeroTest (0 ms)
[----------] 5 tests from MyMathTest (0 ms total)
[----------] Global test environment tear-down
[==========] 5 tests from 1 test suite ran. (0 ms total)
[ PASSED ] 5 tests.
comment:
- Valine
- LiveRe
- ChangYan