前言
在实际项目开发过程中,需要进行必要的单元测试,以保证代码开发阶段的功能性。这里简单介绍下 google 跨平台的c++单元测试框架 gtest。
安装
gtest 编译需要 cmake 支持,安装步骤如下:
1 | $ git clone https://github.com/google/googletest.git |
测试
gtest 提供了TEST()宏,用来定义测试函数:
1 | TEST(test_suite_name, test_case_name) |
在测试函数中,gtest 提供了 EXPECT_*
和 ASSERT_*
两种风格的断言。如果 ASSERT_*
执行失败了,会导致测试函数立即返回;但 EXPECT_*
如果执行失败了,并不会导致测试函数返回。
ASSERT | EXPECT | ESTIMATE | ||
---|---|---|---|---|
ASSERT_TRUE(condition); | EXPECT_TRUE(condition); | condition为true | ||
ASSERT_FALSE(condition); | EXPECT_FALSE(condition); | condition为false | ||
ASSERT_EQ(expected, actual); | EXPECT_EQ(expected, actual); | expected == actual | ||
ASSERT_NE(val1, val2); | EXPECT_NE(val1, val2); | val1 != val2 | ||
ASSERT_LT(val1, val2); | EXPECT_LT(val1, val2); | val1 < val2 | ||
ASSERT_LE(val1, val2); | EXPECT_LE(val1, val2); | val1 <= val2 | ||
ASSERT_GT(val1, val2); | EXPECT_GT(val1, val2); | val1 > val2 | ||
ASSERT_GE(val1, val2); | EXPECT_GE(val1, val2); | val1 >= val2 | ||
ASSERT_STREQ(expected_str, actual_str); | EXPECT_STREQ(expected_str, actual_str); | the two C strings have the same content | ||
ASSERT_STRNE(str1, str2); | EXPECT_STRNE(str1, str2); | the two C strings have different content | ||
ASSERT_STRCASEEQ(expected_str, actual_str); | EXPECT_STRCASEEQ(expected_str, actual_str); | the two C strings have the same content, ignoring case | ||
ASSERT_STRCASENE(str1, str2); | EXPECT_STRCASENE(str1, str2); | the two C strings have different content, ignoring case | ||
|
- 编写简单的测试用例
1 | #include <gtest/gtest.h> |
- CMakeLists.txt
1 | cmake_minimum_required (VERSION 3.2) |
执行测试用例
1
2
3
4
5
6
7
8
9$ make test
Running tests...
Test project /work/temp/gtest-demo/build
Start 1: Test
1/1 Test #1: Test ............................. Passed 0.00 sec
100% tests passed, 0 tests failed out of 1
Total Test time (real) = 0.00 secsamples
gtest 的源码中包含很多测试 samples,并且在 docs 中有简短的说明,以 sample1 为例,实现了阶乘和质数的方法。
1 | // Returns n! (the factorial of n). For negative n, n! is defined to be 1. |
对应阶乘方法的单元测试用例如下:
1 | // Tests factorial of negative numbers. |
编译 samples 需要指定编译选项 cmake -Dgtest_build_samples=ON ${GTEST_DIR}
1 | $ ./sample1_unittest |
总结
利用 gtest 可以快速进行单元测试编写,验证软件开发过程中的问题,是软件开发中不可缺少的环节。