---
description: C++ Testing
alwaysApply: false
---

# C++ Testing

Test behavior. Test edge cases. Test with sanitizers. No excuses.

## Framework Stack

Google Test/Catch2 (test framework), Google Mock (mocking), Google Benchmark (micro-benchmarks), ASan/UBSan/TSan/MSan (sanitizers), Valgrind (leak detection)

## Test Structure (Google Test)

```cpp
TEST_F(OrderServiceTest, Create_WithValidItems_ReturnsOrder) {
    EXPECT_CALL(*inventory_, check_availability("SKU-001", 2))
        .WillOnce(Return(true));
    EXPECT_CALL(*repo_, save(testing::_))
        .WillOnce(Return(Order{.id = "order-1"}));

    auto result = sut_->create(CreateOrderRequest{
        .customer_id = "cust-1", .items = {{"SKU-001", 2}}});

    ASSERT_TRUE(result.has_value());
    EXPECT_EQ(result->customer_id, "cust-1");
}
```

## Catch2

```cpp
TEST_CASE("Parser handles edge cases", "[parser]") {
    SECTION("empty input returns error") {
        auto result = parse("");
        REQUIRE_FALSE(result.has_value());
    }
    SECTION("valid input returns parsed value") {
        auto result = parse("42");
        REQUIRE(*result == 42);
    }
}
```

## Parameterized Tests

```cpp
INSTANTIATE_TEST_SUITE_P(ParseTests, ParseTest, ::testing::Values(
    ParseTestCase{"42", 42},
    ParseTestCase{"", std::unexpected{ParseError::empty_input}},
    ParseTestCase{"abc", std::unexpected{ParseError::invalid_format}}
));
```

## Sanitizers Are Mandatory

```bash
cmake -B build -DENABLE_SANITIZERS=ON  # ASan + UBSan
cmake -B build-tsan -DENABLE_TSAN=ON   # TSan (separate, incompatible with ASan)
cmake --build build && ctest --test-dir build
```

Every sanitizer finding is a real bug. No exceptions.

## Anti-Patterns

- **Tests depending on execution order** — each test must be independent
- **Testing private implementation** — test public interface and observable behavior
- **Ignoring sanitizer warnings** — every ASan/UBSan/TSan finding is a real bug
