{"slug":"cpp-testing","title":"cpp-testing","summary":"Use only when writing/updating/fixing C++ tests, configuring GoogleTest/CTest, diagnosing failing or flaky tests, or adding coverage/sanitizers.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:31.252701Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: cpp-testing\ndescription: Use only when writing/updating/fixing C++ tests, configuring GoogleTest/CTest, diagnosing failing or flaky tests, or adding coverage/sanitizers.\nmetadata:\norigin: ECC</h2>\n<h1>C++ Testing (Agent Skill)</h1>\n<p>Agent-focused testing workflow for modern C++ (C++17/20) using GoogleTest/GoogleMock with CMake/CTest.</p>\n<h2>When to Use</h2>\n<ul>\n<li>Writing new C++ tests or fixing existing tests</li>\n<li>Designing unit/integration test coverage for C++ components</li>\n<li>Adding test coverage, CI gating, or regression protection</li>\n<li>Configuring CMake/CTest workflows for consistent execution</li>\n<li>Investigating test failures or flaky behavior</li>\n<li>Enabling sanitizers for memory/race diagnostics</li>\n</ul>\n<h3>When NOT to Use</h3>\n<ul>\n<li>Implementing new product features without test changes</li>\n<li>Large-scale refactors unrelated to test coverage or failures</li>\n<li>Performance tuning without test regressions to validate</li>\n<li>Non-C++ projects or non-test tasks</li>\n</ul>\n<h2>Core Concepts</h2>\n<ul>\n<li><strong>TDD loop</strong>: red → green → refactor (tests first, minimal fix, then cleanups).</li>\n<li><strong>Isolation</strong>: prefer dependency injection and fakes over global state.</li>\n<li><strong>Test layout</strong>: <code>tests/unit</code>, <code>tests/integration</code>, <code>tests/testdata</code>.</li>\n<li><strong>Mocks vs fakes</strong>: mock for interactions, fake for stateful behavior.</li>\n<li><strong>CTest discovery</strong>: use <code>gtest_discover_tests()</code> for stable test discovery.</li>\n<li><strong>CI signal</strong>: run subset first, then full suite with <code>--output-on-failure</code>.</li>\n</ul>\n<h2>TDD Workflow</h2>\n<p>Follow the RED → GREEN → REFACTOR loop:</p>\n<ol>\n<li><strong>RED</strong>: write a failing test that captures the new behavior</li>\n<li><strong>GREEN</strong>: implement the smallest change to pass</li>\n<li><strong>REFACTOR</strong>: clean up while tests stay green</li>\n</ol>\n<pre><code>// tests/add_test.cpp\n#include &lt;gtest/gtest.h&gt;\n\nint Add(int a, int b); // Provided by production code.\n\nTEST(AddTest, AddsTwoNumbers) { // RED\n  EXPECT_EQ(Add(2, 3), 5);\n}\n\n// src/add.cpp\nint Add(int a, int b) { // GREEN\n  return a + b;\n}\n\n// REFACTOR: simplify/rename once tests pass\n</code></pre>\n<h2>Code Examples</h2>\n<h3>Basic Unit Test (gtest)</h3>\n<pre><code>// tests/calculator_test.cpp\n#include &lt;gtest/gtest.h&gt;\n\nint Add(int a, int b); // Provided by production code.\n\nTEST(CalculatorTest, AddsTwoNumbers) {\n    EXPECT_EQ(Add(2, 3), 5);\n}\n</code></pre>\n<h3>Fixture (gtest)</h3>\n<pre><code>// tests/user_store_test.cpp\n// Pseudocode stub: replace UserStore/User with project types.\n#include &lt;gtest/gtest.h&gt;\n#include &lt;memory&gt;\n#include &lt;optional&gt;\n#include &lt;string&gt;\n\nstruct User { std::string name; };\nclass UserStore {\npublic:\n    explicit UserStore(std::string /*path*/) {}\n    void Seed(std::initializer_list&lt;User&gt; /*users*/) {}\n    std::optional&lt;User&gt; Find(const std::string &amp;/*name*/) { return User{\"alice\"}; }\n};\n\nclass UserStoreTest : public ::testing::Test {\nprotected:\n    void SetUp() override {\n        store = std::make_unique&lt;UserStore&gt;(\":memory:\");\n        store-&gt;Seed({{\"alice\"}, {\"bob\"}});\n    }\n\n    std::unique_ptr&lt;UserStore&gt; store;\n};\n\nTEST_F(UserStoreTest, FindsExistingUser) {\n    auto user = store-&gt;Find(\"alice\");\n    ASSERT_TRUE(user.has_value());\n    EXPECT_EQ(user-&gt;name, \"alice\");\n}\n</code></pre>\n<h3>Mock (gmock)</h3>\n<pre><code>// tests/notifier_test.cpp\n#include &lt;gmock/gmock.h&gt;\n#include &lt;gtest/gtest.h&gt;\n#include &lt;string&gt;\n\nclass Notifier {\npublic:\n    virtual ~Notifier() = default;\n    virtual void Send(const std::string &amp;message) = 0;\n};\n\nclass MockNotifier : public Notifier {\npublic:\n    MOCK_METHOD(void, Send, (const std::string &amp;message), (override));\n};\n\nclass Service {\npublic:\n    explicit Service(Notifier &amp;notifier) : notifier_(notifier) {}\n    void Publish(const std::string &amp;message) { notifier_.Send(message); }\n\nprivate:\n    Notifier &amp;notifier_;\n};\n\nTEST(ServiceTest, SendsNotifications) {\n    MockNotifier notifier;\n    Service service(notifier);\n\n    EXPECT_CALL(notifier, Send(\"hello\")).Times(1);\n    service.Publish(\"hello\");\n}\n</code></pre>\n<h3>CMake/CTest Quickstart</h3>\n<pre><code># CMakeLists.txt (excerpt)\ncmake_minimum_required(VERSION 3.20)\nproject(example LANGUAGES CXX)\n\nset(CMAKE_CXX_STANDARD 20)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\n\ninclude(FetchContent)\n# Prefer project-locked versions. If using a tag, use a pinned version per project policy.\nset(GTEST_VERSION v1.17.0) # Adjust to project policy.\nFetchContent_Declare(\n  googletest\n  # Google Test framework (official repository)\n  URL https://github.com/google/googletest/archive/refs/tags/${GTEST_VERSION}.zip\n)\nFetchContent_MakeAvailable(googletest)\n\nadd_executable(example_tests\n  tests/calculator_test.cpp\n  src/calculator.cpp\n)\ntarget_link_libraries(example_tests GTest::gtest GTest::gmock GTest::gtest_main)\n\nenable_testing()\ninclude(GoogleTest)\ngtest_discover_tests(example_tests)\n</code></pre>\n<pre><code>cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug\ncmake --build build -j\nctest --test-dir build --output-on-failure\n</code></pre>\n<h2>Running Tests</h2>\n<pre><code>ctest --test-dir build --output-on-failure\nctest --test-dir build -R ClampTest\nctest --test-dir build -R \"UserStoreTest.*\" --output-on-failure\n</code></pre>\n<pre><code>./build/example_tests --gtest_filter=ClampTest.*\n./build/example_tests --gtest_filter=UserStoreTest.FindsExistingUser\n</code></pre>\n<h2>Debugging Failures</h2>\n<ol>\n<li>Re-run the single failing test with gtest filter.</li>\n<li>Add scoped logging around the failing assertion.</li>\n<li>Re-run with sanitizers enabled.</li>\n<li>Expand to full suite once the root cause is fixed.</li>\n</ol>\n<h2>Coverage</h2>\n<p>Prefer target-level settings instead of global flags.</p>\n<pre><code>option(ENABLE_COVERAGE \"Enable coverage flags\" OFF)\n\nif(ENABLE_COVERAGE)\n  if(CMAKE_CXX_COMPILER_ID MATCHES \"GNU\")\n    target_compile_options(example_tests PRIVATE --coverage)\n    target_link_options(example_tests PRIVATE --coverage)\n  elseif(CMAKE_CXX_COMPILER_ID MATCHES \"Clang\")\n    target_compile_options(example_tests PRIVATE -fprofile-instr-generate -fcoverage-mapping)\n    target_link_options(example_tests PRIVATE -fprofile-instr-generate)\n  endif()\nendif()\n</code></pre>\n<p>GCC + gcov + lcov:</p>\n<pre><code>cmake -S . -B build-cov -DENABLE_COVERAGE=ON\ncmake --build build-cov -j\nctest --test-dir build-cov\nlcov --capture --directory build-cov --output-file coverage.info\nlcov --remove coverage.info '/usr/*' --output-file coverage.info\ngenhtml coverage.info --output-directory coverage\n</code></pre>\n<p>Clang + llvm-cov:</p>\n<pre><code>cmake -S . -B build-llvm -DENABLE_COVERAGE=ON -DCMAKE_CXX_COMPILER=clang++\ncmake --build build-llvm -j\nLLVM_PROFILE_FILE=\"build-llvm/default.profraw\" ctest --test-dir build-llvm\nllvm-profdata merge -sparse build-llvm/default.profraw -o build-llvm/default.profdata\nllvm-cov report build-llvm/example_tests -instr-profile=build-llvm/default.profdata\n</code></pre>\n<h2>Sanitizers</h2>\n<pre><code>option(ENABLE_ASAN \"Enable AddressSanitizer\" OFF)\noption(ENABLE_UBSAN \"Enable UndefinedBehaviorSanitizer\" OFF)\noption(ENABLE_TSAN \"Enable ThreadSanitizer\" OFF)\n\nif(ENABLE_ASAN)\n  add_compile_options(-fsanitize=address -fno-omit-frame-pointer)\n  add_link_options(-fsanitize=address)\nendif()\nif(ENABLE_UBSAN)\n  add_compile_options(-fsanitize=undefined -fno-omit-frame-pointer)\n  add_link_options(-fsanitize=undefined)\nendif()\nif(ENABLE_TSAN)\n  add_compile_options(-fsanitize=thread)\n  add_link_options(-fsanitize=thread)\nendif()\n</code></pre>\n<h2>Flaky Tests Guardrails</h2>\n<ul>\n<li>Never use <code>sleep</code> for synchronization; use condition variables or latches.</li>\n<li>Make temp directories unique per test and always clean them.</li>\n<li>Avoid real time, network, or filesystem dependencies in unit tests.</li>\n<li>Use deterministic seeds for randomized inputs.</li>\n</ul>\n<h2>Best Practices</h2>\n<h3>DO</h3>\n<ul>\n<li>Keep tests deterministic and isolated</li>\n<li>Prefer dependency injection over globals</li>\n<li>Use <code>ASSERT_*</code> for preconditions, <code>EXPECT_*</code> for multiple checks</li>\n<li>Separate unit vs integration tests in CTest labels or directories</li>\n<li>Run sanitizers in CI for memory and race detection</li>\n</ul>\n<h3>DON'T</h3>\n<ul>\n<li>Don't depend on real time or network in unit tests</li>\n<li>Don't use sleeps as synchronization when a condition variable can be used</li>\n<li>Don't over-mock simple value objects</li>\n<li>Don't use brittle string matching for non-critical logs</li>\n</ul>\n<h3>Common Pitfalls</h3>\n<ul>\n<li><strong>Using fixed temp paths</strong> → Generate unique temp directories per test and clean them.</li>\n<li><strong>Relying on wall clock time</strong> → Inject a clock or use fake time sources.</li>\n<li><strong>Flaky concurrency tests</strong> → Use condition variables/latches and bounded waits.</li>\n<li><strong>Hidden global state</strong> → Reset global state in fixtures or remove globals.</li>\n<li><strong>Over-mocking</strong> → Prefer fakes for stateful behavior and only mock interactions.</li>\n<li><strong>Missing sanitizer runs</strong> → Add ASan/UBSan/TSan builds in CI.</li>\n<li><strong>Coverage on debug-only builds</strong> → Ensure coverage targets use consistent flags.</li>\n</ul>\n<h2>Optional Appendix: Fuzzing / Property Testing</h2>\n<p>Only use if the project already supports LLVM/libFuzzer or a property-testing library.</p>\n<ul>\n<li><strong>libFuzzer</strong>: best for pure functions with minimal I/O.</li>\n<li><strong>RapidCheck</strong>: property-based tests to validate invariants.</li>\n</ul>\n<p>Minimal libFuzzer harness (pseudocode: replace ParseConfig):</p>\n<pre><code>#include &lt;cstddef&gt;\n#include &lt;cstdint&gt;\n#include &lt;string&gt;\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {\n    std::string input(reinterpret_cast&lt;const char *&gt;(data), size);\n    // ParseConfig(input); // project function\n    return 0;\n}\n</code></pre>\n<h2>Alternatives to GoogleTest</h2>\n<ul>\n<li><strong>Catch2</strong>: header-only, expressive matchers</li>\n<li><strong>doctest</strong>: lightweight, minimal compile overhead</li>\n</ul>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":9175,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:56:14.487629Z","sha256":"619783D99BE80906D8DD8750DDA7EFCB5BAF5D27C526FA140C4C3113E3DC2502","sizeBytes":4565},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/cpp-testing","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"7E7B05F88EB7919577787F8DCEEA89C648AFC54F3A3066E8D7DDAF219F37E4C2","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T17:01:34.911055Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/cpp-testing"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}