googletest 学习笔记

前言

googletest 是由 Google 开发的开源 C++ 单元测试框架,在很多开源项目中(如 chromium)都有使用。

这篇博客记录在了自己在学习 googletest 的文档《Primer》和《AdvancedGuide》时做的一些笔记,主要是自己对 googletest 的一些特性的理解和总结。

正如在《漫谈单元测试》这篇博客中所说,googletest 的核心就是一些判断真假的宏,至于 googletest 提供的其他特性,如 Test Fixtures之类,只是它为我们提供的在使用这些宏时遇到的一些常见需求(如,不同 Test 之间共享资源)的通用解决方案。

所以 googletest 的学习并不复杂,但真正想用好单元测试,这只是一个开始。

笔记

Basic Concepts

一些基本概念

assertion
test
test case
test fixture class
nonfatal failure
fatal failure

Assertions

Google Test assertions are macros that resemble function calls. You test a class or function by making assertions about its behavior. When an assertion fails, Google Test prints the assertion’s source file and line number location, along with a failure message. You may also supply a custom failure message which will be appended to Google Test’s message.

googletest 提供的 Assertion 有很多种,但常用主要是下面三种:

直接判断测试结果为 True 或者 False,如 ASSERT_TRUE
将测试结果与预定值比较,如 ASSERT_EQ
比较两个 C string,如 ASSERT_STREQ

Test Fixtures: Using the Same Data Configuration for Multiple Tests

Test Fixtures 用于在多个 Test 之间共享一份数据和代码。很常规的思想,但这里 googletest 把它抽象到了 Test Case 这一层,作为开发人员,我们只需要关心 Test Fixtures 的具体实现就可以了,而不用担心一个 Test Fixtures 对象的创建和释放。

下面是关于 Test Fixtures 的一些需要注意的点:

Different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one.

More Assertions

一些不常用的 Assertion,主要分为如下三种:

单纯的表示成功或者产生一个失败
测试特定的代码块有没有抛出指定的异常
能够定制测试成功或失败时的输出消息

Predicate Assertions for Better Error Messages

下面是文档中所说的为什么要引入这种 Assertion 的说法:

Sometimes a user has to use EXPECT_TRUE() to check a complex expression, for lack of a better macro. This has the problem of not showing you the values of the parts of the expression, making it hard to understand what went wrong.

但实际情况并不是这样。下面是使用 EXPECT_PRED2 和 EXPECT_GT 进行同样的判断在失败时两者分别输出的信息:

// EXPECT\_GT 输出的信息
../samples/sample1_unittest.cc:90: Failure
Expected: (Factorial(-10)) > (2), actual: 1 vs 2

// EXPECT\_PRED2 输出的信息
../samples/sample1_unittest.cc:94: Failure
MyGreater(Factorial(-10), 2) evaluates to false, where
Factorial(-10) evaluates to 1
2 evaluates to 2

123456789

如上所述,并没有出现文档中所说的情况,而且 EXPECT_GT 输出的信息比 EXPECT_PRED2 输出的信息更简洁。

另外,这小节涉及到

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...