cpp-testing

cpp-testing

熱門

僅在撰寫/更新/修復 C++ 測試、設定 GoogleTest/CTest、診斷失敗或不穩定的測試,或新增涵蓋率/消毒器時使用。

23萬星標
3.5萬分支
更新於 2026/7/14
SKILL.md
readonlyread-only
name
cpp-testing
description

僅在撰寫/更新/修復 C++ 測試、設定 GoogleTest/CTest、診斷失敗或不穩定的測試,或新增涵蓋率/消毒器時使用。

C++ 測試(Agent 技能)

專為 Agent 設計的現代 C++(C++17/20)測試工作流程,使用 GoogleTest/GoogleMock 搭配 CMake/CTest。

使用時機

  • 撰寫新的 C++ 測試或修復現有測試
  • 設計 C++ 元件的單元/整合測試涵蓋率
  • 新增測試涵蓋率、CI 閘門或回歸保護
  • 設定 CMake/CTest 工作流程以確保一致執行
  • 調查測試失敗或不穩定行為
  • 啟用消毒器進行記憶體/競爭診斷

不應使用時機

  • 實作新產品功能但未涉及測試變更
  • 與測試涵蓋率或失敗無關的大規模重構
  • 效能調校但無測試回歸可驗證
  • 非 C++ 專案或非測試任務

核心概念

  • TDD 循環:紅 → 綠 → 重構(先寫測試,最小修復,再清理)。
  • 隔離:偏好依賴注入和假物件,避免全域狀態。
  • 測試佈局tests/unittests/integrationtests/testdata
  • Mock 與 Fake:Mock 用於互動驗證,Fake 用於有狀態行為。
  • CTest 發現:使用 gtest_discover_tests() 以穩定發現測試。
  • CI 訊號:先執行子集,再以 --output-on-failure 執行完整套件。

TDD 工作流程

遵循 RED → GREEN → REFACTOR 循環:

  1. RED:撰寫一個失敗的測試,捕捉新行為
  2. GREEN:實作最小的變更以通過測試
  3. REFACTOR:在測試保持綠燈的同時清理程式碼
// tests/add_test.cpp
#include <gtest/gtest.h>

int Add(int a, int b); // 由生產程式碼提供。

TEST(AddTest, AddsTwoNumbers) { // RED
  EXPECT_EQ(Add(2, 3), 5);
}

// src/add.cpp
int Add(int a, int b) { // GREEN
  return a + b;
}

// REFACTOR:測試通過後簡化/重新命名

程式碼範例

基本單元測試(gtest)

// tests/calculator_test.cpp
#include <gtest/gtest.h>

int Add(int a, int b); // 由生產程式碼提供。

TEST(CalculatorTest, AddsTwoNumbers) {
    EXPECT_EQ(Add(2, 3), 5);
}

Fixture(gtest)

// tests/user_store_test.cpp
// 虛擬碼存根:請以專案類型取代 UserStore/User。
#include <gtest/gtest.h>
#include <memory>
#include <optional>
#include <string>

struct User { std::string name; };
class UserStore {
public:
    explicit UserStore(std::string /*path*/) {}
    void Seed(std::initializer_list<User> /*users*/) {}
    std::optional<User> Find(const std::string &/*name*/) { return User{"alice"}; }
};

class UserStoreTest : public ::testing::Test {
protected:
    void SetUp() override {
        store = std::make_unique<UserStore>(":memory:");
        store->Seed({{"alice"}, {"bob"}});
    }

    std::unique_ptr<UserStore> store;
};

TEST_F(UserStoreTest, FindsExistingUser) {
    auto user = store->Find("alice");
    ASSERT_TRUE(user.has_value());
    EXPECT_EQ(user->name, "alice");
}

Mock(gmock)

// tests/notifier_test.cpp
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>

class Notifier {
public:
    virtual ~Notifier() = default;
    virtual void Send(const std::string &message) = 0;
};

class MockNotifier : public Notifier {
public:
    MOCK_METHOD(void, Send, (const std::string &message), (override));
};

class Service {
public:
    explicit Service(Notifier &notifier) : notifier_(notifier) {}
    void Publish(const std::string &message) { notifier_.Send(message); }

private:
    Notifier &notifier_;
};

TEST(ServiceTest, SendsNotifications) {
    MockNotifier notifier;
    Service service(notifier);

    EXPECT_CALL(notifier, Send("hello")).Times(1);
    service.Publish("hello");
}

CMake/CTest 快速入門

# CMakeLists.txt(節錄)
cmake_minimum_required(VERSION 3.20)
project(example LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(FetchContent)
# 偏好專案鎖定的版本。若使用標籤,請依專案政策使用固定版本。
set(GTEST_VERSION v1.17.0) # 請依專案政策調整。
FetchContent_Declare(
  googletest
  # Google Test 框架(官方儲存庫)
  URL https://github.com/google/googletest/archive/refs/tags/${GTEST_VERSION}.zip
)
FetchContent_MakeAvailable(googletest)

add_executable(example_tests
  tests/calculator_test.cpp
  src/calculator.cpp
)
target_link_libraries(example_tests GTest::gtest GTest::gmock GTest::gtest_main)

enable_testing()
include(GoogleTest)
gtest_discover_tests(example_tests)
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug
cmake --build build -j
ctest --test-dir build --output-on-failure

執行測試

ctest --test-dir build --output-on-failure
ctest --test-dir build -R ClampTest
ctest --test-dir build -R "UserStoreTest.*" --output-on-failure
./build/example_tests --gtest_filter=ClampTest.*
./build/example_tests --gtest_filter=UserStoreTest.FindsExistingUser

除錯失敗

  1. 使用 gtest 過濾器重新執行單一失敗測試。
  2. 在失敗的斷言周圍加入範圍日誌。
  3. 啟用消毒器重新執行。
  4. 根因修復後擴展至完整套件。

涵蓋率

偏好目標層級設定而非全域旗標。

option(ENABLE_COVERAGE "啟用涵蓋率旗標" OFF)

if(ENABLE_COVERAGE)
  if(CMAKE_CXX_COMPILER_ID MATCHES "GNU")
    target_compile_options(example_tests PRIVATE --coverage)
    target_link_options(example_tests PRIVATE --coverage)
  elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
    target_compile_options(example_tests PRIVATE -fprofile-instr-generate -fcoverage-mapping)
    target_link_options(example_tests PRIVATE -fprofile-instr-generate)
  endif()
endif()

GCC + gcov + lcov:

cmake -S . -B build-cov -DENABLE_COVERAGE=ON
cmake --build build-cov -j
ctest --test-dir build-cov
lcov --capture --directory build-cov --output-file coverage.info
lcov --remove coverage.info '/usr/*' --output-file coverage.info
genhtml coverage.info --output-directory coverage

Clang + llvm-cov:

cmake -S . -B build-llvm -DENABLE_COVERAGE=ON -DCMAKE_CXX_COMPILER=clang++
cmake --build build-llvm -j
LLVM_PROFILE_FILE="build-llvm/default.profraw" ctest --test-dir build-llvm
llvm-profdata merge -sparse build-llvm/default.profraw -o build-llvm/default.profdata
llvm-cov report build-llvm/example_tests -instr-profile=build-llvm/default.profdata

消毒器

option(ENABLE_ASAN "啟用 AddressSanitizer" OFF)
option(ENABLE_UBSAN "啟用 UndefinedBehaviorSanitizer" OFF)
option(ENABLE_TSAN "啟用 ThreadSanitizer" OFF)

if(ENABLE_ASAN)
  add_compile_options(-fsanitize=address -fno-omit-frame-pointer)
  add_link_options(-fsanitize=address)
endif()
if(ENABLE_UBSAN)
  add_compile_options(-fsanitize=undefined -fno-omit-frame-pointer)
  add_link_options(-fsanitize=undefined)
endif()
if(ENABLE_TSAN)
  add_compile_options(-fsanitize=thread)
  add_link_options(-fsanitize=thread)
endif()

不穩定測試防護

  • 絕不使用 sleep 進行同步;改用條件變數或閂鎖。
  • 每個測試使用唯一的暫存目錄,並務必清理。
  • 在單元測試中避免真實時間、網路或檔案系統依賴。
  • 對隨機輸入使用確定性種子。

最佳實踐

應做

  • 保持測試確定性且隔離
  • 偏好依賴注入而非全域變數
  • 使用 ASSERT_* 作為前置條件,EXPECT_* 進行多重檢查
  • 在 CTest 標籤或目錄中區分單元測試與整合測試
  • 在 CI 中執行消毒器以檢測記憶體和競爭

不應做

  • 不要在單元測試中依賴真實時間或網路
  • 不要使用 sleep 作為同步手段,當條件變數可用時
  • 不要過度 mock 簡單的值物件
  • 不要對非關鍵日誌使用脆弱的字串比對

常見陷阱

  • 使用固定暫存路徑 → 每個測試產生唯一的暫存目錄並清理。
  • 依賴真實時間 → 注入時鐘或使用虛擬時間來源。
  • 不穩定的並發測試 → 使用條件變數/閂鎖和有限等待。
  • 隱藏的全域狀態 → 在 fixture 中重設全域狀態或移除全域變數。
  • 過度 mock → 對有狀態行為偏好 fake,僅 mock 互動。
  • 缺少消毒器執行 → 在 CI 中加入 ASan/UBSan/TSan 建置。
  • 僅在除錯建置中啟用涵蓋率 → 確保涵蓋率目標使用一致的旗標。

選擇性附錄:模糊測試 / 屬性測試

僅在專案已支援 LLVM/libFuzzer 或屬性測試函式庫時使用。

  • libFuzzer:最適合純函數且 I/O 極少的情況。
  • RapidCheck:基於屬性的測試,驗證不變量。

最小 libFuzzer harness(虛擬碼:請取代 ParseConfig):

#include <cstddef>
#include <cstdint>
#include <string>

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    std::string input(reinterpret_cast<const char *>(data), size);
    // ParseConfig(input); // 專案函數
    return 0;
}

GoogleTest 的替代方案

  • Catch2:標頭檔 only,表達式豐富的匹配器
  • doctest:輕量級,最小編譯開銷