# Catch

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

[Catch2](https://github.com/catchorg/Catch2) 是一个轻量级的测试框架。 该名称代表  C++ Automated Test Cases in Headers (version two) 。 CLion 支持 Catch 版本 1.7.2 及更高版本。

与 [Boost.Test](boost-test-support.html) 一样，Catch2 不提供模拟功能。 但是，您可以将其与独立的模拟框架结合使用，例如 [Hippomocks](https://github.com/dascandy/hippomocks)、 [FakeIt](https://github.com/eranpeer/FakeIt) 或 [Trompeloeil](https://github.com/rollbear/trompeloeil)。

> **Note:**
> 有关使用 Catch 的 CMake 集成的更多信息，请参阅 [本教程](https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#top)。

## Catch2 基础

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

### 示例测试

以下示例展示了一个使用 Catch2 编写的简单测试：

```CPLUSPLUS
#define CATCH_CONFIG_MAIN // provides main(); this line is required in only one .cpp file
#include "catch_amalgamated.hpp"

int theAnswer() { return 6*9; } // function to be tested

TEST_CASE( "Life, the universe and everything", "[42][theAnswer]" ) {
REQUIRE(theAnswer() == 42);
}

```

在上述示例中，  `Life, the universe and everything`  是一个自由格式的测试名称，必须是唯一的。  `TEST_CASE`  宏的第二个参数是两个标签  `[42]`  和  `[theAnswer]`  的组合。 测试名称和标签都是常规字符串，不限于有效的 C++ 标识符。 您可以通过指定通配符测试名称或标签表达式来运行测试集合。

注意断言行  `REQUIRE(theAnswer() == 42)` 。 与其他框架不同，Catch2 没有用于捕获各种条件形式的断言集合。 相反，它解析条件表达式的实际 C/C++ 代码，并使用它来描述结果：

```CONSOLE
...Failure:
REQUIRE(theAnswer() == 42)
with expansion:
54 == 42
```

`要求`  宏在失败时中止测试，而替代的  `检查`  宏仅报告失败并让测试继续。 在这两个宏中，您可以使用所有 C++ 比较运算符，并以任意顺序传递参数。

### 部分

Catch2 的另一个重要功能是组织测试的方法：在 [用例和部分](https://github.com/catchorg/Catch2/blob/master/docs/tutorial.md#test-cases-and-sections) 中（同时也 [支持](https://github.com/catchorg/Catch2/blob/master/docs/test-fixtures.md) 基于类的固定机制）。 请看文档中的这个示例：

```CPLUSPLUS
TEST_CASE( "vectors can be sized and resized", "[vector]" ) {

// initialization block executed for each section
std::vector<int> v( 5 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
// end of initialization block

SECTION( "resizing bigger changes size and capacity" ) {
v.resize( 10 );

REQUIRE( v.size() == 10 );
REQUIRE( v.capacity() >= 10 );
}
SECTION( "resizing smaller changes size but not capacity" ) {
v.resize( 0 );

REQUIRE( v.size() == 0 );
REQUIRE( v.capacity() >= 5 );
}
}

```

在上述代码片段中，  `TEST_CASE`  在每个  `SECTION`  开始时执行。 在  `TEST_CASE`  顶部的两个  `要求`  语句强制  `size`  为 5，  `capacity`  在每个部分的入口处至少为 5。 通过这种方式，共享对象分配在堆栈上，无需为其创建固定类。 在每次通过  `TEST_CASE`  时，Catch2 执行一个部分并跳过其他部分。 下一次，它执行第二个部分，依此类推。

部分可以嵌套以创建检查操作的序列。 每个叶子部分（内部没有嵌套部分的部分）只执行一次。 当父部分失败时，它会阻止子部分运行。 例如：

```CPLUSPLUS
SECTION( "reserving bigger changes capacity but not size" ) {
v.reserve( 10 );

REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 10 );

// verify that attempting to reserve a smaller capacity changes nothing
SECTION( "reserving smaller again does not change capacity" ) {
v.reserve( 7 );
REQUIRE( v.capacity() >= 10 );
}
}

```

Catch2 还支持用于测试用例和部分的替代 [BDD 风格语法](https://github.com/catchorg/Catch2/blob/master/docs/test-cases-and-sections.md#bdd-style-test-cases)。

### 模板测试

Catch2 支持以下宏形式的类型参数化测试用例：

* `TEMPLATE_TEST_CASE( test name , tags, type1, type2, ..., typen )`

* `TEMPLATE_PRODUCT_TEST_CASE( test name , tags, (template-type1, template-type2, ..., template-typen), (template-arg1, template-arg2, ..., template-argm) )`

* `TEMPLATE_LIST_TEST_CASE( test name, tags, type list )`

这些宏的行为与常规  `TEST_CASE`  相同，但会针对每种类型或类型组合运行。 有关更多信息，请参阅 [类型参数化测试用例](https://github.com/catchorg/Catch2/blob/master/docs/test-cases-and-sections.md#type-parametrised-test-cases)。

除了类型参数化测试用例，Catch2 还提供  `TEMPLATE_TEST_CASE_SIG`  和  `TEMPLATE_PRODUCT_TEST_CASE_SIG`  用于创建基于签名的参数化测试用例，其语法类似，但增加了  签名  参数：

```CPLUSPLUS
TEMPLATE_TEST_CASE_SIG( test name , tags, signature, type1, type2, ..., typen )
```

有关更多信息，请参阅 [基于签名的参数化测试用例](https://github.com/catchorg/Catch2/blob/master/docs/test-cases-and-sections.md#signature-based-parametrised-test-cases)。

## 在 CLion 中使用 Catch2

Procedure: 将 Catch2 添加到您的项目中

1. 按照 [本指南](https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#top) 中的说明，使用 CMake 集成开始使用 Catch。

Procedure: 运行/调试自动创建的 Catch 配置

CLion 会检测您项目中的 Catch 测试并为其创建运行/调试配置。

1. 您可以立即使用此配置运行或调试项目中的所有 Catch 测试：

![自动创建的 Catch 配置](https://resources.jetbrains.com/help/img/idea/2026.3/cl_catch_autocreated_config.png)

Procedure: 添加新的 Catch 运行/调试配置

1. 转到   运行 | 编辑配置  。

2. 点击 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.expui.general.add.svg) 并从模板列表中选择   Catch  。

![添加 Catch 配置](https://resources.jetbrains.com/help/img/idea/2026.3/cl_catch_config_templateslist.png)

3. ![Catch 运行/调试配置](https://resources.jetbrains.com/help/img/idea/2026.3/cl_catchTest3.png)

* 在 名称 字段中设置配置名称。 此名称将显示在可用运行/调试配置的列表中。

* 选择 标签/测试 选项以运行特定标签或所有标签的测试。 选择 Pattern 选项以运行特定模式的所有测试。

* 在 选项卡 字段中指定标签。 此字段仅在选择了 标签/测试 选项时可用。

* 从 测试 列表中选择所需的测试。 此选项仅在提供了一个或多个标签时可用。

* 在 Pattern 字段中指定模式名称。 此字段仅在选择了 Pattern 选项时可用。

* 在 目标 字段中，从可用目标列表中选择所需的目标。

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

4. 点击   Apply   以保存配置。

5. 在切换器中选择新创建的配置并运行 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.expui.run.run.svg) 或调试 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app.expui.run.debug.svg)。

![运行/调试 Catch 配置](https://resources.jetbrains.com/help/img/idea/2026.3/cl_catch_config_switcher.png)

Procedure: 运行测试

* 运行或调试单个测试或整个套件/固定装置的最快方法是使用边栏图标：

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

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

> **Tip:**
> 有关更多信息，请参阅 [运行、调试、终止测试](performing-tests.html)。

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

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

Procedure: 查看测试结果

当您运行测试时，CLion 会在内置的 [测试运行窗口](viewing-and-exploring-test-results.html) 中显示结果和过程。 测试树显示所有测试，并逐一执行。 测试运行器窗口包括：

* 进度条 ，显示到目前为止已执行测试的百分比，

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

* 测试的输出流，

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

![测试运行窗口](https://resources.jetbrains.com/help/img/idea/2026.3/cl_catchtest_testrunner.png)

Procedure: 指定随机种子

如果您在 Catch 测试中使用了随机化，您可以通过指定  `--rng-seed='time'|'random-device'|'number'`  参数来设置初始种子。 有关详细信息，请参阅 Catch 文档中的 [本节](https://github.com/catchorg/Catch2/blob/devel/docs/command-line.md#specify-a-seed-for-the-random-number-generator)。

1. 在主菜单中，转到  `运行 | 编辑配置`  并选择任何 Catch 配置。 种子参数将用于整个测试运行。

2. 在   程序参数   字段中，设置  `--rng-seed`  标志：

![指定 rng-seed](https://resources.jetbrains.com/help/img/idea/2026.3/cl_tests_catch_rngseed_config.png)

3. 运行配置，您将在测试树中看到固定种子：

![具有固定 rng-seed 的测试结果](https://resources.jetbrains.com/help/img/idea/2026.3/cl_tests_catch_rngseed_result.png)

4. 使用上下文菜单以相同的固定种子重新运行测试：

![使用固定种子重新运行测试](https://resources.jetbrains.com/help/img/idea/2026.3/cl_tests_catch_rndseed_rerun.png)

> **Note:**
> 如果您希望保留先前生成的种子，请不要使用 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app-client.expui.run.rerun.svg)、 ![](https://resources.jetbrains.com/help/img/idea/2026.3/app-client.expui.run.restartFailedTests.svg) 或配置重新运行测试。

## 故障排除：测试名称过长会导致列表错误并终止测试运行

如果您的项目中有较长的测试名称，这可能会破坏列表并终止整个测试运行（请参阅 [此](https://github.com/catchorg/Catch2/issues/2751) Catch 问题）。 尝试以下解决方案之一：

* 打开 `catch_user_config.hpp` 文件并将 `#define CATCH_CONFIG_CONSOLE_WIDTH` 参数从 `80` 更改为 `800` 。

* 打开 `CatchConfigOptions.cmake` 文件并将配置生成器从 ```CMAKE set(CATCH_CONFIG_CONSOLE_WIDTH "80" ...) ``` 为 ```CMAKE set(CATCH_CONFIG_CONSOLE_WIDTH "800" ...) ```

* （最不推荐）在 CLion 中禁用测试列表提取：清除 `cidr.test.prepare.test.list` 注册表项。 使用 `帮助 | 查找操作` `Ctrl+Shift+A` (Windows), `⌘ ⇧ A` (macOS), `⌘ ⇧ A` (IntelliJ IDEA Classic (macOS)), `⌘ ⇧ P` (macOS System Shortcuts), `Ctrl+Shift+A` (XWin), `Ctrl+Shift+A` (GNOME), `Ctrl+Shift+A` (KDE), `Escape, X` (Emacs), `Ctrl+Shift+P` (Sublime Text), `⌘ ⇧ P` (Sublime Text (macOS)), `⌘ ⇧ A` (Xcode), `Ctrl+Shift+A` (Visual Studio), `⌘ ⇧ A` (Visual Studio (macOS)), `Ctrl+Shift+A` (ReSharper), `⌘ ⇧ A` (ReSharper (macOS)), `Ctrl+Shift+A` (QtCreator), `⌘ ⇧ A` (QtCreator (macOS)), `Ctrl+I` (NetBeans), `Ctrl+Shift+A` (Eclipse), `⌘ 3` (Eclipse (macOS)) 打开注册表对话框。

## See also

### 快速开始

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

### 流程

[Run/Debug/Terminate Tests](performing-tests.html) [Explore Test Results](viewing-and-exploring-test-results.html)

