Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

testing-patterns

БесплатноБез исполняемых скриптовНе проверен

Patterns for testing code effectively. Use when breaking dependencies for testability, adding tests to existing code, understanding unfamiliar code through…

joelhooksот joelhooks★ 755 звёзд на GitHub18 установок в других каталогах

Об этом скилле

Testing Patterns

Core insight: Code without tests is hard to change safely. The Testing Dilemma: to change code safely you need tests, but to add tests you often need to change code first.

The Seam Model

A seam is a place where you can alter behavior without editing the source file.

Every seam has an enabling point - the place where you decide which behavior to use.

Seam Types (Best to Worst)

Object Seams (preferred in OO languages):

// Original - hard dependency
class PaymentProcessor {
  process(amount: number) {
    const gateway = new StripeGateway(); // untestable
    return gateway.charge(amount);
  }
}

// With seam - injectable dependency
class PaymentProcessor {
  constructor(private gateway: PaymentGateway = new StripeGateway()) {}

  process(amount: number) {
    return this.gateway.charge(amount); // enabling point: constructor
  }
}

Link Seams (classpath/module resolution):

  • Enabling point is outside program text (build scripts, import maps)
  • Swap implementations at link time
  • Useful but harder to notice

Preprocessing Seams (C/C++ only):

  • #include and #define manipulation
  • Last resort - avoid in modern languages

Characterization Tests

Purpose: Document what code actually does, not what it should do.

Process:

  1. Write a test you know will fail
  2. Run it - let the failure tell you actual behavior
  3. Change the test to expect actual behavior
  4. Repeat until you've characterized the code
// Step 1: Write failing test
test("calculateFee returns... something", () => {
  const result = calculateFee(100, "premium");
  expect(result).toBe(0); // will fail, tells us actual value
});

// Step 2: After failure shows "Expected 0, got 15"
test("calculateFee returns 15 for premium with 100", () => {
  const result = calculateFee(100, "premium");
  expect(result).toBe(15); // now documents actual behavior
});

Key insight: Characterization tests verify behaviors ARE present, enabling safe refactoring. They're not about correctness - they're about preservation.

Breaking Dependencies

When You Can't Instantiate a Class

Parameterize Constructor - externalize dependencies:

// Before
class MailChecker {
  constructor(checkPeriod: number) {
    this.receiver = new MailReceiver(); // hidden dependency
  }
}

// After - add parameter with default
class MailChecker {
  constructor(
    checkPeriod: number,
    receiver: MailReceiver = new MailReceiver(),
  ) {
    this.receiver = receiver;
  }
}

Extract Interface - safest dependency break:

// 1. Create interface from class
interface MessageReceiver {
  receive(): Message[];
}

// 2. Have original implement it
class MailReceiver implements MessageReceiver { ... }

// 3. Create test double
class FakeReceiver implements MessageReceiver {
  messages: Message[] = [];
  receive() { return this.messages; }
}

Subclass and Override Method - core technique:

// Production class with problematic method
class OrderProcessor {
  protected getDatabase(): Database {
    return new ProductionDatabase(); // can't use in tests
  }

  process(order: Order) {
    const db = this.getDatabase();
    // ... processing logic
  }
}

// Testing subclass
class TestableOrderProcessor extends OrderProcessor {
  protected getDatabase(): Database {
    return new InMemoryDatabase(); // test-friendly
  }
}

Sensing vs Separation

Sensing: Need to verify effects of code (what did it do?) Separation: Need to run code independently (isolate from dependencies)

Choose technique based on which problem you're solving.

Adding New Behavior Safely

Sprout Method

Add new behavior in a new method, call it from existing code:

// Before - need to add validation
function processOrder(order: Order) {
  // ... 200 lines of untested code
  saveOrder(order);
}

// After - sprout new tested method
function validateOrder(order: Order): ValidationResult {
  // New code, fully tested
}

function processOrder(order: Order) {
  const validation = validateOrder(order); // one new line
  if (!validation.valid) return;
  // ... 200 lines of untested code
  saveOrder(order);
}

Sprout Class

When new behavior doesn't fit existing class:

// New class for new behavior
class OrderValidator {
  validate(order: Order): ValidationResult { ... }
}

// Minimal change to existing code
function processOrder(order: Order) {
  const validator = new OrderValidator();
  if (!validator.validate(order).valid) return;
  // ... existing untested code
}

Wrap Method

Rename existing method, create new method that wraps it:

// Before
function pay(employees: Employee[]) {
  for (const e of employees) {
    e.pay();
  }
}

// After - wrap with logging
function pay(employees: Employee[]) {
  logPayment(employees); // new behavior
  dispatchPay(employees); // renamed original
}

functio
Полный SKILL.md на GitHub

Установить testing-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/dependency-breaking-catalog.md

FAQ

Что делает скилл testing-patterns?

Patterns for testing code effectively. Use when breaking dependencies for testability, adding tests to existing code, understanding unfamiliar code through characterization tests, or deciding how to structure tests. Covers seams, dependency injection, test doubles, and safe refactoring techniques from Michael Feathers.

Как установить скилл testing-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл testing-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить testing-patterns с