Skills

Cpp Testing

仅在创建/更新/修复 C++ 测试、配置 GoogleTest/CTest、诊断失败或不稳定的测试、以及添加覆盖率或消毒器时使用。

Install

npx skills add xu-xiang/everything-claude-code-zh --skill cpp-testing -g -a claude-code -y
Category
Engineering
Updated
8mo ago
License
MIT
Context cost
Mediumabout 1,808 tokens
Runs scripts
No, instructions only

What it does

仅在创建/更新/修复 C++ 测试、配置 GoogleTest/CTest、诊断失败或不稳定的测试、以及添加覆盖率或消毒器时使用。

C++ Testing(智能体技能)

这是一个基于 CMake/CTest 和 GoogleTest/GoogleMock 的、面向智能体(Agent)的现代 C++(C++17/20)测试工作流(Workflow)。

使用场景

  • 创建新的 C++ 测试或修改现有测试
  • 为 C++ 组件设计单元测试/集成测试覆盖率
  • 添加测试覆盖率、CI 门禁和回归保护
  • 配置 CMake/CTest 工作流以实现一致的执行
  • 调查测试失败或不稳定(Flaky)的行为
  • 启用消毒器(Sanitizers)进行内存/竞态诊断

不建议使用的场景

  • 实现不涉及测试更改的新产品功能
  • 与测试覆盖率或失败无关的大规模重构
  • 没有需要验证的测试回归的性能调优
  • 非 C++ 项目或非测试任务

核心概念

  • TDD 循环: 红(Red) → 绿(Green) → 重构(Refactor)(测试先行,最小化修复,然后清理代码)
  • 解耦: 优先使用依赖注入(Dependency Injection)和伪造对象(Fakes),而非全局状态
  • 测试布局: tests/unit、tests/integration、tests/testdata
  • 模拟 (Mock) vs 伪造 (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;
};
Read the whole SKILL.md on GitHub

More in Engineering