# Google Test

> For the complete documentation index, see [llms.txt](https://www.jetbrains.com/zh-cn/help/clion/llms.txt).

[Google Test](https://github.com/google/googletest) 和 [Google Mock](https://github.com/google/googlemock) 是一对强大的单元测试工具：该框架是可移植的，包含丰富的致命和非致命断言，提供创建测试夹具和测试组的工具，提供信息丰富的消息，并以 XML 格式导出结果。 可能唯一的缺点是需要在您的项目中构建  gtest/gmock  才能使用它。

## Google Test 基础

如果您不熟悉 Google Test，您可以在下方找到其主要概念的描述：

### 断言

在 Google Test 中，用于检查条件是否为 true 的语句称为 [断言](https://github.com/google/googletest/blob/master/docs/primer.md#assertions)。 非致命断言的名称中带有  `EXPECT_`  前缀，而导致致命失败并中止执行的断言名称以  `ASSERT_`  开头。 例如：

```CPLUSPLUS
TEST (SquareTest /*test suite name*/, PosZeroNeg /*test name*/) {
EXPECT_EQ (9.0, (3.0*2.0)); // fail, test continues
ASSERT_EQ (0.0, (0.0));     // success
ASSERT_EQ (9, (3)*(-3.0));  // fail, test interrupts
ASSERT_EQ (-9, (-3)*(-3.0));// not executed due to the previous assert
}

```

以下列出了 Google Test 中可用的一些断言（在此表中，  `ASSERT_`  作为示例给出，可与  `EXPECT_`  互换）：

|  逻辑  |      `ASSERT_TRUE(condition)`         `ASSERT_FALSE(condition)`      |
|  通用比较  |      `ASSERT_EQ(expected, actual) / ASSERT_NE(val1, val2)`         `ASSERT_LT(val1, val2) / ASSERT_LE(val1, val2)`         `ASSERT_GT(val1, val2) / ASSERT_GE(val1, val2)`      |
|  浮点比较  |      `ASSERT_FLOAT_EQ(expected, actual)`         `ASSERT_DOUBLE_EQ(expected, actual)`         `ASSERT_NEAR(val1, val2, abs_error)`      |
|  字符串比较  |      `ASSERT_STREQ(expected_str, actual_str) / ASSERT_STRNE(str1, str2)`         `ASSERT_STRCASEEQ(expected_str, actual_str) / ASSERT_STRCASENE(str1, str2)`      |
|  异常检查  |      `ASSERT_THROW(statement, exception_type)`         `ASSERT_ANY_THROW(statement)`         `ASSERT_NO_THROW(statement)`      |

此外，Google Test 支持 [谓词断言](https://github.com/google/googletest/blob/master/docs/advanced.md#predicate-assertions-for-better-error-messages)，这有助于使输出消息更具信息性。 例如，可以使用谓词函数来检查  `a`  和  `b`  是否等价并返回布尔结果，而不是使用  `EXPECT_EQ(a, b)` 。 在失败的情况下，断言将打印函数参数的值：

|       谓词断言示例         ```CPLUSPLUS bool IsEq(int a, int b){ if (a==b) return true; else return false; }  TEST(BasicChecks, TestEq) { int a = 0; int b = 1; EXPECT_EQ(a, b); EXPECT_PRED2(IsEq, a, b); } ```    |       输出         ```CONSOLE Failure Value of: b Actual: 1 Expected: a Which is: 0  Failure IsEq(a, b) evaluates to false, where a evaluates to 0 b evaluates to 1  ```    |

在上面的  `EXPECT_PRED2`  中，  predN  是一个具有 N 个参数的谓词函数。 Google Test 当前支持最多 5 个参数的谓词断言。

### 夹具

共享公共对象或子例程的 Google 测试可以分组到测试夹具中。 以下是一个通用测试夹具的示例：

```CPLUSPLUS
class myTestFixture: public ::testing::test {
public:
myTestFixture( ) {
// initialization;
// can also be done in SetUp()
}

void SetUp( ) {
// initialization or some code to run before each test
}

void TearDown( ) {
// code to run after each test;
// can be used instead of a destructor,
// but exceptions can be handled in this function only
}

~myTestFixture( )  {
//resources cleanup, no exceptions allowed
}

// shared user data
};

```

当用于测试夹具时，应将  `TEST()`  宏替换为  `TEST_F()` ，以允许测试访问测试夹具的成员和函数：

```CPLUSPLUS
TEST_F( myTestFixture, TestName) {/*...*/}

```

有关 Google Test 的更多信息，请在框架的存储库中查看 [示例](https://github.com/google/googletest/blob/master/docs/samples.md)。 此外，有关其他显著的 Google Test 功能（如 [值参数化测试](https://github.com/google/googletest/blob/master/docs/advanced.md#value-parameterized-tests) 和 [类型参数化测试](https://github.com/google/googletest/blob/master/docs/advanced.md#type-parameterized-tests)）的更多信息，请参阅 [高级选项](https://github.com/google/googletest/blob/master/docs/advanced.md#advanced-googletest-topics)。

## 将 Google Test 添加到您的项目中

Procedure:

1. 从官方 [仓库](https://github.com/google/googletest) 下载 Google Test，并将   googletest-main   的内容解压到项目中的空文件夹中（例如，  `Google_tests/lib` ）。

或者，将 Google Test 克隆为 [Git 子模块](https://git-scm.com/book/en/v2/Git-Tools-Submodules)，或 [使用 CMake 下载](https://github.com/google/googletest/tree/master/googletest#incorporating-into-an-existing-cmake-project)（以下说明不适用于后一种情况）。

2. 在   Google_tests   文件夹中创建一个  `CMakeLists.txt`  文件：在项目树中右键点击它并选择  `新建 | CMakeLists.txt` 。

自定义以下行并将其添加到您的脚本中：

```CMAKE
# 'Google_test' is the subproject name
project(Google_tests)

# 'lib' is the folder with Google Test sources
add_subdirectory(lib)
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})

# 'Google_Tests_run' is the target name
# 'test1.cpp test2.cpp' are source files with tests
add_executable(Google_Tests_run test1.cpp test2.cpp)
target_link_libraries(Google_Tests_run gtest gtest_main)

```

3. 在您的   root    `CMakeLists.txt`  脚本中，将  `add_subdirectory(Google_tests)`  命令添加到末尾，然后重新加载项目。

编写测试时，请确保在每个包含测试代码的  `.cpp`  文件开头添加  `#include "gtest/gtest.h"` 。

> **Tip:**
> 请查看这个 [示例](unit-testing-tutorial.html#adding-framework)，位于   单元测试教程   中。

## Google Test 运行/调试配置

尽管 Google Test 提供了  `main()`  条目，并且您可以像常规应用程序一样运行测试，但我们建议使用专用的 Google Test 运行/调试配置。 它包括与测试相关的设置，并让您受益于内置的 [测试运行器](#test-runner)，这在将测试作为常规程序运行时不可用。

> **Note:**
> CLion 会为每个与  `gtest`  或  `gmock`  链接的 CMake 目标自动创建一个 Google Test 配置。

Procedure:

1. 要创建一个 Google Test 配置，请在主菜单中转到   运行 | 编辑配置  ，点击 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.expui.general.add.svg) 并从模板列表中选择   Google Test  。

2. 指定要包含在配置中的测试或套件，或者提供用于过滤测试名称的模式。 字段中提供了自动完成功能，可帮助您快速填写它们：

![配置字段中的自动补全](https://resources.jetbrains.com/help/img/idea/2026.3/cl_googletest_config_completion.png)

设置通配符以指定测试模式，例如：

![测试模式](https://resources.jetbrains.com/help/img/idea/2026.3/cl_googletest_config_pattern.png)

> **Tip:**
> Pattern   控件在底层使用 [gtest-filter](https://github.com/google/googletest/blob/master/docs/advanced.md#running-a-subset-of-the-tests)。 例如，如果您如上所示指定了  `Abs*` ，CLion 将添加  `--gtest_filter=Abs*`  标志。

3. 在配置设置的其他字段中，您可以设置环境变量和命令行选项。 例如，使用   程序参数   字段传递  `--gtest_repeat`  标志并多次运行 Google 测试：

![程序参数中的测试标志](https://resources.jetbrains.com/help/img/idea/2026.3/cl_UTtutorial_configs_flags.png)

输出将如下所示：

```CONSOLE
Repeating all tests (iteration 1) ...
Repeating all tests (iteration 2) ...
Repeating all tests (iteration 3) ...
                           
```

4. 保存配置后，它就可以用于   运行   ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.actions.execute.svg) 或   调试   ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.actions.startDebugger.svg)。

> **Note:**
> 与其编辑单个配置，您可以   修改 Google Test 模板本身  。 在这种情况下，您指定的设置将作为默认值应用于所有此类型的新配置。

## 运行测试

在 CLion 中，有 [多种方式](performing-tests.html) 启动测试的运行/调试会话，其中一种是使用特殊的边栏图标。 这些图标帮助快速运行或调试单个测试或整个套件/夹具：

![测试的侧边栏图标](https://resources.jetbrains.com/help/img/idea/2026.3/cl_UTtutorial_guttericons.png)

边栏图标还会显示测试结果（如果已可用）：成功 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.runConfigurations.testState.green2.svg) 或失败 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.runConfigurations.testState.red2.svg)。

使用装订区域图标运行测试/套件/固定例程时，CLion 会创建一个 [临时](run-debug-configuration.html) Google Test 配置，该配置在配置列表中显示为灰色。 要保存临时配置，请在  `编辑配置`  对话框中选择它并按 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.expui.general.save.svg)。

![保存临时测试配置](https://resources.jetbrains.com/help/img/idea/2026.3/cl_UTturorial_temporaryconfigs_save.png)

## 探索结果

当您运行测试时，结果（以及过程）会显示在测试运行器窗口中。 此窗口包括：

* 进度条 ，显示已执行测试的百分比，

* 树视图 ，显示所有正在运行的测试及其状态和持续时间，

* 测试的 输出 流，

* 工具栏 ，提供重新运行失败的 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.runConfigurations.testState.red2.svg)测试、导出 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.expui.general.export.svg)或打开自动保存的先前结果 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.vcs.history.svg)的选项，按字母顺序排序测试 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.objectBrowser.sorted.svg)以便轻松找到特定测试，或按持续时间排序 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.runConfigurations.sortbyDuration.svg)以了解哪个测试运行时间比其他测试更长。

测试树显示所有测试，同时它们一个接一个地执行。 对于参数化测试，您还将在树中看到参数。 此外，树中还包括已禁用的测试（名称中带有  `DISABLED`  前缀的测试），并使用相应图标将它们标记为已跳过。

![Google 测试的测试运行器](https://resources.jetbrains.com/help/img/idea/2026.3/cl_googletest_runner.png)

## 在运行时跳过测试

您可以根据运行时评估的条件配置某些测试被跳过。 为此，请使用  `GTEST_SKIP()`  宏。

> **Note:**
> Google Test 从版本 1.10.0 开始支持此功能，因此请确保更新项目中的框架源代码。

将条件语句和  `GTEST_SKIP()`  宏添加到您想要跳过的测试中：

```CPLUSPLUS
TEST(Foo, Bar) {
    //...
    if (condition)
        GTEST_SKIP_("message"); // or GTEST_SKIP() with no message
    //...
}
```

使用   显示已忽略   ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.runConfigurations.showIgnored.svg) 图标在测试运行器树中查看/隐藏已跳过的测试：

![测试运行器选项卡中的已跳过测试](https://resources.jetbrains.com/help/img/idea/2026.3/cl_google_test_skip.png)

## See also

### 快速开始

[单元测试教程](unit-testing-tutorial.html) [快速 CMake 教程](quick-cmake-tutorial.html)

### 流程

[运行、调试、终止测试](performing-tests.html) [查看测试结果](viewing-and-exploring-test-results.html)

