Catch2
一、框架簡介
Catch2 是一個基于 C++ 的現代化單元測試框架,支持 TDD(測試驅動開發)和 BDD(行為驅動開發)模式。其核心優勢在于:
- 單頭文件設計:v2.x 版本僅需包含 catch.hpp 即可使用
- 自然語法:測試用例命名支持自由格式字符串,斷言使用標準 C++ 運算符
- 零外部依賴:僅需 C++11 及以上標準庫支持
- 多維度覆蓋:支持異常測試、基準測試、Matchers 匹配器等高級功能
官方網站Catch2
二、環境配置
# CMake 集成示例(v2.x 版本)
cmake_minimum_required(VERSION 3.10)
project(Catch2_Demo)# 下載 Catch2 單頭文件
include(FetchContent)
FetchContent_Declare(Catch2URL https://github.com/catchorg/Catch2/releases/download/v3.8.0/catch_amalgamated.hpp
)
FetchContent_MakeAvailable(Catch2)add_executable(tests src/main.cpp src/tests.cpp
)
target_include_directories(tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
三、核心功能實現
- 基礎測試結構
// tests.cpp
#define CATCH_CONFIG_MAIN
#include <catch.hpp> int factorial(int n) {if(n <= 0) return 1;return n * factorial(n - 1);
}TEST_CASE("階乘基礎測試", "[math][factorial]") {SECTION("正整數值驗證") {REQUIRE(factorial(5) == 120);CHECK(factorial(6) == 720); // 非致命斷言 }SECTION("邊界條件驗證") {REQUIRE(factorial(0) == 1);REQUIRE(factorial(-1) == 1);}
}
- BDD 風格測試
SCENARIO("用戶登錄流程驗證", "[auth][bdd]") {GIVEN("已注冊用戶憑證") {std::string username = "test_user";std::string password = "P@ssw0rd";WHEN("輸入正確密碼") {bool result = authenticate(username, password);THEN("應返回認證成功") {REQUIRE(result == true);}}WHEN("輸入錯誤密碼") {bool result = authenticate(username, "wrong_pass");THEN("應返回認證失敗") {REQUIRE_FALSE(result);}}}
}
- 高級驗證功能
// 異常測試
TEST_CASE("異常處理驗證", "[exceptions]") {REQUIRE_THROWS_AS(throw std::runtime_error("錯誤"), std::runtime_error);CHECK_THROWS_WITH(throw "Error!", Catch::Contains("Error"));
}// 浮點近似比較
TEST_CASE("精度計算驗證", "[math][approx]") {double pi = 3.14159265359;REQUIRE(pi == Approx(3.14159).epsilon(0.0001));
}// Matchers 匹配器
TEST_CASE("字符串驗證", "[strings]") {using namespace Catch::Matchers;std::string url = "https://api.example.com/v1"; REQUIRE_THAT(url, StartsWith("https") && EndsWith("v1") && Contains("example"));
}
- 基準測試
TEST_CASE("性能基準測試", "[!benchmark]") {BENCHMARK("向量插入 1000 元素") {std::vector<int> v;for(int i = 0; i < 1000; ++i) {v.push_back(i); }};
}
四、進階使用技巧
- 測試過濾:通過標簽執行特定測試
./tests "[math]" # 執行所有數學測試
./tests "~[slow]" # 排除標記為 slow 的測試
- 自定義 Main 函數(需配置 CATCH_CONFIG_RUNNER):
int main(int argc, char* argv[]) {Catch::Session session;// 添加全局配置 session.configData().showDurations = Catch::ShowDurations::Always;return session.run(argc, argv);
}
- 參數化測試:
TEST_CASE_METHOD(TestFixture, "參數化測試", "[params]") {auto [input, expected] = GENERATE(std::make_tuple(2, 4),std::make_tuple(3, 9),std::make_tuple(5, 25));REQUIRE(square(input) == expected);
}
五、最佳實踐建議
- 測試組織結構:
tests/
├── unit/ # 單元測試
├── integration/ # 集成測試
└── benchmark/ # 性能測試
- CI/CD 集成:
# GitHub Actions 示例
jobs:test:runs-on: ubuntu-latest steps:- uses: actions/checkout@v2- run: |mkdir build cd build cmake ..make ./tests -r compact
完整代碼
Github
作者 | 鄭天佐 | |
郵箱 | zhengtianzuo06@163.com | |
主頁 | http://www.zhengtianzuo.com | |
github | https://github.com/zhengtianzuo |