0%

googletest自动化测试框架

Googletest 是Google的测试技术 团队开发的一个C++测试框架。它支持任何类型的测试,而不仅仅是单元测试。

一个好的测试框架应该有以下特点。

  • 测试应该是独立且可重复的。也就是可以再不同的对象上进行隔离测试,当遇到测试失败的时候,可以单独快速的对其进行调试。
  • 测试应该组织良好,并且能反应所测试的代码的结构。
  • 测试应该是轻量级的和可以重复使用的。
  • 当测试失败时,能提供有关问题尽可能多的错误信息。
  • 测试框架应当将编写测试代码的开发人员从繁琐的事情从解放出来,从而专注于测试的内容。
  • 测试应该很快速。

下面介绍Googletest中的几个宏函数。

断言

Googletest中的断言类似于函数调用宏。通过类或者函数的行为做出断言,失败的时候会打印出对应的源文件和行号的位置。

ASSERT_*版本的宏遇到一个失败的测试案例的时候会产生一个致命的错误,从而终止当前的测试函数。

EXPECT_*版本的宏则遇到一个失败的测试案例的时候则会产生一个不是那么致命的错误,当然也不会终止当前的测试函数。

自定义错误消息:Googletest是可以自定义错误消息,也很简单,直接使用运算符<<将错误消息重定向到宏中就可以了。

1
2
3
4
ASSERT_EQ(x.size(), y.size()) << "Vector x and y are of unequal length";
for(int i=0; i < x.size(); i++){
EXPECT_EQ(x.[i], y.[i]) << "Vector x and y differ at index";
}

我们可以使用Googletest提供的断言来验证程序的各种行为,完整的断言列表可以参看断言列表

常用的以下几个:

1
2
3
4
EXPECT_EQ(a, b)
ASSERT_EQ(a, b)
EXPECT_TRUE(condition)
EXPECT_FALSE(condition)

简单使用

编译安装

首先在官网下载对应版本的googletest代码,下载地址

  • 进入源码目录编译googletest代码cmake CMakeLists.txt

image-20211212042902052

  • 执行make对应的Makefile进行编译安装。
  • 将头文件和依赖库加入系统头文件和库路径(或者将对应路径加入环境变量)
1
2
cp googletest/include/gtest /usr/include
cp lib/* /usr/lib64/

编译测试代码

sample.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "sample.h"
#define true 1
#define false 0

int Factorial(int n){
int result = 1;
for(int i=1; i<=n; i++){
result *= i;
}
return result;
}

// flase return 0, true return 1
int IsPrime(int n){
if (n <= 1) return false;
if (n% 2 == 2) return n == 2;
for (int i = 3; ; i += 2){
if (i > n/i) break;
if (n % i == 0) return false;
}
return true;
}

sample.h

1
2
3
4
5
6
7
#ifndef __GTEST_SAMPLE_H__
#define __GTEST_SAMPLE_H__
// return n!(the factorial of n). for negative n
int Factorial(int n);
int IsPrime(int n);

#endif

samlpe_test.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <limits.h>
#include "sample.h"
#include <gtest/gtest.h>

TEST(FactorialTest, dasd) {
EXPECT_EQ(1, Factorial(-5)) << "dasdaddasdasdadasdadad";
EXPECT_EQ(1, Factorial(-1));
EXPECT_GT(Factorial(-10), 0);
}

TEST(FactorialTest1, dasd) {
EXPECT_EQ(1, Factorial(-5)) << "dasdaddasdasdadasdadad";
EXPECT_EQ(1, Factorial(-1));
EXPECT_GT(Factorial(-10), 0);
}

int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

编译命令:g++ sample.c sample_test.c -lgtest -lpthread

如果不编译main函数可以使用googletest提供的统一的main函数入口,使用如下编译。

g++ sample.c sample_test.c -lgtest -lpthread -lgtest_main

image-20211212045454979

Reference

[1] https://google.github.io/googletest/reference/assertions.html

[2] https://google.github.io/googletest/primer.html

小主,路过打个赏再走呗~