googletest
Google Test (GTest) and Google Mock for C++ unit testing. Covers test fixtures, parameterized tests, typed tests, death tests, matchers, mocks (EXPECT_CALL), and CMake integration via gtest_discover_tests. USE WHEN: user mentions "Google Test", "GTest", "gmock", "EXPECT_EQ", "TEST_F", "INSTANTIATE_TEST_SUITE_P", "EXPECT_CALL", "MOCK_METHOD", "C++ unit test" DO NOT USE FOR: Catch2 (different framework), doctest, Boost.Test, CppUnit
What this skill does
# Google Test - Quick Reference
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `googletest`.
## Basic test
```cpp
#include <gtest/gtest.h>
#include "calc.hpp"
TEST(CalcTest, AddsTwoPositiveNumbers) {
EXPECT_EQ(add(2, 3), 5);
}
TEST(CalcTest, ThrowsOnDivByZero) {
EXPECT_THROW(divide(1, 0), std::invalid_argument);
}
```
`EXPECT_*` continues on failure; `ASSERT_*` aborts the current test.
## Assertions cheat sheet
| Macro | Use |
|-------|-----|
| `EXPECT_EQ(a, b)` / `_NE` / `_LT` / `_LE` / `_GT` / `_GE` | Comparison |
| `EXPECT_TRUE(x)` / `_FALSE` | Boolean |
| `EXPECT_FLOAT_EQ` / `EXPECT_DOUBLE_EQ` / `EXPECT_NEAR(a, b, eps)` | Floating-point |
| `EXPECT_STREQ` / `_STRNE` / `_STRCASEEQ` | C-strings |
| `EXPECT_THROW(stmt, ExType)` / `_NO_THROW` / `_ANY_THROW` | Exceptions |
| `EXPECT_DEATH(stmt, regex)` | Process exits with diagnostic |
| `EXPECT_THAT(value, matcher)` | gmock matchers (see below) |
## Fixtures
```cpp
class DatabaseTest : public ::testing::Test {
protected:
Database db_;
void SetUp() override { db_.connect("memory"); }
void TearDown() override { db_.disconnect(); }
};
TEST_F(DatabaseTest, InsertsRow) {
EXPECT_TRUE(db_.insert({"alice"}));
EXPECT_EQ(db_.count(), 1);
}
```
For one-time setup across all tests in a suite, use `static void SetUpTestSuite()` / `TearDownTestSuite()`.
## Parameterized tests
```cpp
class IsPrimeTest : public ::testing::TestWithParam<int> {};
TEST_P(IsPrimeTest, RecognizesPrimes) {
EXPECT_TRUE(is_prime(GetParam()));
}
INSTANTIATE_TEST_SUITE_P(
SmallPrimes,
IsPrimeTest,
::testing::Values(2, 3, 5, 7, 11, 13)
);
```
Other generators: `Range(1, 10)`, `ValuesIn(container)`, `Combine(...)`, `Bool()`.
## Typed tests (test the same logic across types)
```cpp
template <typename T>
class StackTest : public ::testing::Test {
protected:
Stack<T> stack_;
};
using StackTypes = ::testing::Types<int, std::string, std::vector<int>>;
TYPED_TEST_SUITE(StackTest, StackTypes);
TYPED_TEST(StackTest, PushIncreasesSize) {
this->stack_.push(TypeParam{});
EXPECT_EQ(this->stack_.size(), 1u);
}
```
## gmock matchers (with EXPECT_THAT)
```cpp
#include <gmock/gmock.h>
using ::testing::AllOf;
using ::testing::ElementsAre;
using ::testing::Field;
using ::testing::Ge;
using ::testing::HasSubstr;
using ::testing::Pointee;
EXPECT_THAT(name, HasSubstr("alice"));
EXPECT_THAT(numbers, ElementsAre(1, 2, 3));
EXPECT_THAT(user, AllOf(Field(&User::age, Ge(18)),
Field(&User::name, HasSubstr("bob"))));
EXPECT_THAT(ptr, Pointee(Ge(0)));
```
## gmock - mocking interfaces
```cpp
class IRepo {
public:
virtual ~IRepo() = default;
virtual std::optional<User> find(int id) const = 0;
virtual void save(const User&) = 0;
};
class MockRepo : public IRepo {
public:
MOCK_METHOD(std::optional<User>, find, (int id), (const, override));
MOCK_METHOD(void, save, (const User&), (override));
};
TEST(ServiceTest, ReturnsUserWhenFound) {
MockRepo repo;
EXPECT_CALL(repo, find(42))
.Times(1)
.WillOnce(::testing::Return(User{42, "alice"}));
Service svc{repo};
auto u = svc.get(42);
ASSERT_TRUE(u.has_value());
EXPECT_EQ(u->name, "alice");
}
```
`EXPECT_CALL` matchers: `_` (anything), `Eq(v)`, `Ge(v)`, `NotNull()`, `Truly(pred)`.
Cardinality: `.Times(N)`, `.Times(AtLeast(1))`, `.Times(AnyNumber())`.
Actions: `Return(v)`, `Throw(ex)`, `Invoke(callable)`, `DoAll(SetArgPointee<0>(v), Return(true))`.
## Death tests
```cpp
TEST(SafeDeath, AbortsOnNull) {
EXPECT_DEATH({ deref(nullptr); }, "null pointer");
}
```
Death tests fork the process; keep them small. Use `::testing::FLAGS_gtest_death_test_style = "threadsafe";` if multithreaded.
## CMake integration
```cmake
include(FetchContent)
FetchContent_Declare(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.15.2
GIT_SHALLOW TRUE
)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) # MSVC
FetchContent_MakeAvailable(googletest)
enable_testing()
add_executable(unit_tests tests/calc_test.cpp tests/db_test.cpp)
target_link_libraries(unit_tests PRIVATE mylib GTest::gtest_main GTest::gmock)
include(GoogleTest)
gtest_discover_tests(unit_tests)
```
Run:
```bash
ctest --output-on-failure
ctest -R '^CalcTest\.' --output-on-failure # filter by regex
./build/unit_tests --gtest_filter='*Add*' # binary directly
./build/unit_tests --gtest_repeat=100 --gtest_shuffle
```
## Anti-Patterns
| Anti-Pattern | Why It's Bad | Correct Approach |
|--------------|--------------|------------------|
| Logic in `SetUp` shared across tests | One leaky test poisons others | Construct fresh state per test |
| `TEST` instead of `TEST_F` when fixture exists | No setup hook | Use `TEST_F(FixtureName, Case)` |
| `EXPECT_TRUE(a == b)` | Loses both values in diagnostic | `EXPECT_EQ(a, b)` |
| Floating-point `EXPECT_EQ` | Spurious failures | `EXPECT_NEAR(a, b, eps)` or `EXPECT_DOUBLE_EQ` |
| `EXPECT_CALL` after the fact | gmock requires calls before exercising the mock | Set expectations before calling SUT |
| Strict mocks everywhere | Brittle to harmless extra calls | Use `NiceMock` by default; `StrictMock` when surface is small |
| `MOCK_METHOD` on non-virtual functions | Won't be intercepted | Mock through a virtual interface (or use a template seam) |
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.