单元测试
测试的本质其实都是一样的,都是通过给定参数来执行函数,然后判断函数的实际输出结果和期望输出结果是否一致
测试框架
gtest采用的是xUnit架构,
JUnit
PyUnit: PyUnit 主要用于进行白盒测试和回归测试
C++测试
gtest单元测试是Google的一套用于编写C++测试的框架,
可以运行在很多平台上(包括Linux、Mac OS X、Windows、Cygwin等等)。基于xUnit架构
基本了解
gtest系列之TEST宏
TEST宏的作用是创建一个简单测试,它定义了一个测试函数,在这个函数里可以使用任何C++代码并使用提供的断言来进行检查
#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
#endif
二、gtest系列之断言
gtest中断言的宏可以分为两类:一类是ASSERT宏,另一类就是EXPECT宏了。
1、ASSERT_系列:如果当前点检测失败则退出当前函数
2、EXPECT_系列:如果当前点检测失败则继续往下执行
三:
gtest的事件一共有三种:
1、TestSuite事件
2、TestCase事件
3.全局事件
全局事件
来做一个测试实例,测试Map的find()和size()函数并通过继承testing::Test来实现。
此时的TEST宏必须写成TEST_F,而且它的第一个参数必须与类名一致
1.安装:
lib目录下会生成:libgmock.a libgmock_main.a libgtest.a libgtest_main.a
2.使用
#include "gtest/gtest.h"
01.写main方法,其中调用RUN_ALL_TESTS函数即可。
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
02、我们也可以不用写main函数,那就需要链接 gtest_main.a这个静态库
//测试哪个函数以及这个测试的名字(
TEST(FactorialTest, Negative) {
// This test is named "Negative", and belongs to the "FactorialTest"
// test case.
// 断言,运行Factorial(-5)并对比结果是不是等于1(Factorial(-5)==1?)
EXPECT_EQ(1, Factorial(-5));
EXPECT_EQ(1, Factorial(-1));
// 断言,运行Factorial(-10)并对比结果是不是小于0(0 > actorial(-10)?)
EXPECT_GT(Factorial(-10), 0);
}
3编译运行
编译呢
1、g++ sample1.cc sample1_unittest.cc -lgtest -std=c++14 -lgtest_main -lpthread -o test1
CMakeLists.txt
运行
参考
https://blog.csdn.net/Jacksqh/article/details/129805462
gtest断言类型
ASSERT_*断言和EXPECT_*断言的区别
https://github.com/google/googletest/blob/main/googletest/include/gtest/gtest.h
标签:单元测试,TEST,gtest,EXPECT,测试,Test,main
From: https://www.cnblogs.com/ytwang/p/18085368