wpank

Testing Patterns

開発v0.1.0
作者:wpank更新日 2026-05-11testing-patterns@clawhub_wpank/testing-patterns
テスト生成

AlphaMoatによると、2026-10時点でTesting Patternsのダウンロード数は8,934、スター数は7で、累計ダウンロード数で今回のランキング対象AIスキル10,914件中3,106位、開発では1,069件中245位です。

一覧の初期表示は累計ダウンロード数順で、スター数順にも並べ替えできます。詳細ページの順位は累計ダウンロード数で計算しています。

ダウンロード数
8934
スター数
7
累計ダウンロード順位
#3,106
全体の上位 29% · 開発の上位 23%
プラットフォームダウンロード数スター数コメント
ClawHub ↗62372-
SkillHub ↗89347—

プラットフォームごとに集計方法と集計時点が異なります。

このスキルでできること

準備・実行・検証、パラメーター化、テストダブル、DB分離、APIテスト、依存性注入を扱います。振る舞いを検証し、外部境界を模擬して共有状態や固定待機を避け、回帰テストを加えます。網羅率だけでは有効な検証の代わりになりません。 これはテスト設計のガイダンスと例であり、対象プロジェクトのテストを実行した証拠ではありません。記載された npx インストーラーは未固定のサードパーティー処理を実行するため、実行前にインストール元を確認して固定してください。

資料公開日 2026-10-27

できること

  • テスト戦略や不安定なテストを改善する

使う場面

  • 適切な粒度でコードの振る舞いを確かめるとき

プロンプト例

スキルのドキュメントをもとに生成した例であり、実際の実行結果ではありません。

この関数の振る舞いと境界を分析し、欠陥を捉えるテストと分離方法を提案して。

月次の推移

ダウンロード数8934
3326633893492026-03 · ダウンロード数 37412026-05 · ダウンロード数 49142026-06 · ダウンロード数 51892026-07 · ダウンロード数 55742026-08 · ダウンロード数 58792026-09 · ダウンロード数 63462026-10 · ダウンロード数 893426-0326-0926-10
スター数7
2572026-03 · スター数 22026-05 · スター数 72026-06 · スター数 72026-07 · スター数 72026-08 · スター数 72026-09 · スター数 72026-10 · スター数 726-0326-0926-10

2026-09 から集計方法を変更し、同名スキルを作者ごとに分けて集計し、全スキルを対象にしました。破線は変更前の月で、変更後のデータとは直接比較せず、変更をまたぐ増減も計算していません。

月ダウンロード数前月比スター数
2026-108934—7
2026-096346—7
2026-085879+5.5%7
2026-075574+7.4%7
2026-065189+5.6%7
2026-054914—7
2026-033741—2

SKILL.md 原文

作者が公開した元のファイルをテキストのまま表示しています。AlphaMoat による編集や審査はしていません。リンクはクリックできません。コマンドは内容を確認してから実行してください。取得日 2026-10-23。

14 KB・ClawHub v0.1.0
---
name: testing-patterns
model: standard
category: testing
description: Unit, integration, and E2E testing patterns with framework-specific guidance. Use when asked to "write tests", "add test coverage", "testing strategy", "test this function", "create test suite", "fix flaky tests", or "improve test quality".
version: 1.0
---

# Testing Patterns
すべて表示(全 389 行)
> **Write tests that catch bugs, not tests that pass.** — Confidence through coverage, speed through isolation.

---

## Testing Pyramid

| Level | Ratio | Speed | Cost | Confidence | Scope |
|-------|-------|-------|------|------------|-------|
| **Unit** | ~70% | ms | Low | Low (isolated) | Single function/class |
| **Integration** | ~20% | seconds | Medium | Medium | Module boundaries, APIs, DB |
| **E2E** | ~10% | minutes | High | High (realistic) | Full user workflows |

> **Rule:** If your E2E tests outnumber your unit tests, invert the pyramid.

---

## Unit Testing Patterns

### Core Patterns

| Pattern | When to Use | Structure |
|---------|------------|-----------|
| **Arrange-Act-Assert** | Default for all unit tests | Setup, Execute, Verify |
| **Given-When-Then** | BDD-style, behavior-focused | Precondition, Action, Outcome |
| **Parameterized** | Same logic, multiple inputs | Data-driven test cases |
| **Snapshot** | UI components, serialized output | Compare against saved baseline |
| **Property-Based** | Mathematical invariants | Generate random inputs, assert properties |

### Arrange-Act-Assert (AAA)

The default structure for every unit test. Clear separation of setup, execution, and verification makes tests readable and maintainable.

```typescript
// Clean AAA structure
test('calculates order total with tax', () => {
  // Arrange
  const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }];
  const taxRate = 0.08;

  // Act
  const total = calculateTotal(items, taxRate);

  // Assert
  expect(total).toBe(27.0);
});
```

### Test Doubles

Use the right type of test double for the situation. Each serves a different purpose.

| Double | Purpose | When to Use | Example |
|--------|---------|-------------|---------|
| **Stub** | Returns canned data | Control indirect input | `jest.fn().mockReturnValue(42)` |
| **Mock** | Verifies interactions | Assert something was called | `expect(mock).toHaveBeenCalledWith('arg')` |
| **Spy** | Wraps real implementation | Observe without replacing | `jest.spyOn(service, 'save')` |
| **Fake** | Working simplified impl | Need realistic behavior | In-memory database, fake HTTP server |

```typescript
// Stub — control indirect input
const getUser = jest.fn().mockResolvedValue({ id: 1, name: 'Alice' });

// Spy — observe without replacing
const spy = jest.spyOn(logger, 'warn');
processInvalidInput(data);
expect(spy).toHaveBeenCalledWith('Invalid input received');

// Fake — lightweight substitute
class FakeUserRepo implements UserRepository {
  private users = new Map<string, User>();
  async save(user: User) { this.users.set(user.id, user); }
  async findById(id: string) { return this.users.get(id) ?? null; }
}
```

### Parameterized Tests

Use parameterized tests when the same logic needs verification with multiple inputs. This eliminates copy-paste tests while providing comprehensive coverage.

```typescript
// Vitest/Jest
test.each([
  ['hello', 'HELLO'],
  ['world', 'WORLD'],
  ['', ''],
  ['123abc', '123ABC'],
])('toUpperCase(%s) returns %s', (input, expected) => {
  expect(input.toUpperCase()).toBe(expected);
});
```

```python
# pytest
@pytest.mark.parametrize("input,expected", [
    ("hello", "HELLO"),
    ("world", "WORLD"),
    ("", ""),
])
def test_to_upper(input, expected):
    assert input.upper() == expected
```

```go
// Go — table-driven tests (idiomatic)
func TestAdd(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"positive", 2, 3, 5},
        {"zero", 0, 0, 0},
        {"negative", -1, -2, -3},
    }
    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            if got := Add(tc.a, tc.b); got != tc.expected {
                t.Errorf("Add(%d,%d) = %d, want %d", tc.a, tc.b, got, tc.expected)
            }
        })
    }
}
```

---

## Integration Testing Patterns

### Database Testing Strategies

| Strategy | Approach | Trade-off |
|----------|----------|-----------|
| **Transaction rollback** | Wrap each test in a transaction, rollback after | Fast, but hides commit bugs |
| **Fixtures/seeds** | Load known data before suite | Predictable, but brittle if schema changes |
| **Factory functions** | Generate data programmatically | Flexible, but more setup code |
| **Testcontainers** | Spin up real DB in Docker | Realistic, but slower startup |

```typescript
// Transaction rollback pattern (Prisma)
beforeEach(async () => {
  await prisma.$executeRaw`BEGIN`;
});
afterEach(async () => {
  await prisma.$executeRaw`ROLLBACK`;
});

test('creates user in database', async () => {
  const user = await createUser({ name: 'Alice', email: '[email protected]' });
  const found = await prisma.user.findUnique({ where: { id: user.id } });
  expect(found?.name).toBe('Alice');
});
```

### API Testing

```typescript
// Supertest (Node.js)
import request from 'supertest';
import { app } from '../src/app';

describe('POST /api/users', () => {
  it('creates a user and returns 201', async () => {
    const res = await request(app)
      .post('/api/users')
      .send({ name: 'Alice', email: '[email protected]' })
      .expect(201);

    expect(res.body).toMatchObject({
      id: expect.any(String),
      name: 'Alice',
    });
  });

  it('returns 400 for invalid email', async () => {
    await request(app)
      .post('/api/users')
      .send({ name: 'Alice', email: 'not-an-email' })
      .expect(400);
  });
});
```

---

## Mocking Best Practices

### Mock Boundaries, Not Implementations

The fundamental rule: mock at system boundaries (external APIs, databases, file systems) and never mock internal domain logic.

```typescript
// BAD — mocking internal implementation
jest.mock('./utils/formatDate');  // Breaks on refactor

// GOOD — mocking external boundary
jest.mock('./services/paymentGateway');  // Third-party API is the boundary
```

### When to Mock vs Not Mock

| Mock | Don't Mock |
|------|-----------|
| HTTP APIs, external services | Pure functions |
| Database (in unit tests) | Your own domain logic |
| File system, network | Data transformations |
| Time/Date (`Date.now`) | Simple calculations |
| Environment variables | Internal class methods |

### Dependency Injection for Testability

Structure code so dependencies can be swapped in tests. This is the single most impactful pattern for testable code.

```typescript
// Injectable dependencies — easy to test
class OrderService {
  constructor(
    private paymentGateway: PaymentGateway,
    private inventory: InventoryService,
    private notifier: NotificationService,
  ) {}

  async placeOrder(order: Order): Promise<OrderResult> {
    const stock = await this.inventory.check(order.items);
    if (!stock.available) return { status: 'out_of_stock' };

    const payment = await this.paymentGateway.charge(order.total);
    if (!payment.success) return { status: 'payment_failed' };

    await this.notifier.send(order.userId, 'Order confirmed');
    return { status: 'confirmed', id: payment.transactionId };
  }
}

// In tests — inject fakes
const service = new OrderService(
  new FakePaymentGateway(),
  new FakeInventory({ available: true }),
  new FakeNotifier(),
);
```

---

## Framework Quick Reference

| Framework | Language | Type | Test Runner | Assertion |
|-----------|----------|------|-------------|-----------|
| **Jest** | JS/TS | Unit/Integration | Built-in | `expect()` |
| **Vitest** | JS/TS | Unit/Integration | Vite-native | `expect()` (Jest-compatible) |
| **Playwright** | JS/TS/Python | E2E | Built-in | `expect()` / locators |
| **Cypress** | JS/TS | E2E | Built-in | `cy.should()` |
| **pytest** | Python | Unit/Integration | Built-in | `assert` |
| **Go testing** | Go | Unit/Integration | `go test` | `t.Error()` / testify |
| **Rust** | Rust | Unit/Integration | `cargo test` | `assert!()` / `assert_eq!()` |
| **JUnit 5** | Java/Kotlin | Unit/Integration | Built-in | `assertEquals()` |
| **RSpec** | Ruby | Unit/Integration | Built-in | `expect().to` |
| **PHPUnit** | PHP | Unit/Integration | Built-in | `$this->assert*()` |
| **xUnit** | C# | Unit/Integration | Built-in | `Assert.Equal()` |

---

## Test Quality Checklist

| Quality | Rule | Why |
|---------|------|-----|
| **Deterministic** | Same input produces same result, every time | Flaky tests erode trust |
| **Isolated** | No shared mutable state between tests | Order-dependent tests break in CI |
| **Fast** | Unit: < 10ms, Integration: < 1s, E2E: < 30s | Slow tests don't get run |
| **Readable** | Test name describes the scenario and expectation | Tests are documentation |
| **Maintainable** | Change one behavior, change one test | Brittle tests slow development |
| **Focused** | One logical assertion per test | Failures pinpoint the problem |

> **Naming convention:** `test_[unit]_[scenario]_[expected result]` or `should [do X] when [condition Y]`

---

## Coverage Strategy

### When to Aim for What

| Target | When | Rationale |
|--------|------|-----------|
| **80%+ line coverage** | Business logic, utilities, core domain | High ROI — catches most regressions |
| **90%+ branch coverage** | Payment processing, auth, security-critical | Edge cases matter here |
| **100% coverage** | Almost never — diminishing returns | Getter/setter tests add noise, not confidence |
| **Mutation testing** | Critical paths after coverage is high | Verifies tests actually catch bugs |

### What NOT to Test

| Skip | Reason |
|------|--------|
| Generated code (Prisma client, protobuf) | Maintained by tooling |
| Third-party library internals | Not your responsibility |
| Simple getters/setters | No logic to verify |
| Configuration files | Test the behavior they configure instead |
| Console.log / print statements | Side effects with no business value |

---

## Test Organization

```
src/
├── services/
│   ├── order.service.ts
│   └── order.service.test.ts      # Co-located unit tests
├── api/
│   └── routes/
│       └── orders.ts
tests/
├── integration/
│   ├── api/
│   │   └── orders.test.ts         # API integration tests
│   └── db/
│       └── order.repo.test.ts     # DB integration tests
├── e2e/
│   ├── pages/                     # Page objects
│   │   └── checkout.page.ts
│   └── specs/
│       └── checkout.spec.ts       # E2E specs
└── helpers/
    ├── factories.ts               # Test data factories
    └── setup.ts                   # Global test setup
```

> **Rule:** Co-locate unit tests with source. Separate integration and E2E tests into dedicated directories.

---

## Anti-Patterns

| Anti-Pattern | Problem | Fix |
|--------------|---------|-----|
| **Testing implementation** | Tests break on refactor, not on bugs | Test behavior and outputs, not internals |
| **Flaky tests** | Non-deterministic failures erode CI trust | Remove time/order/network dependencies |
| **Test pollution** | Shared mutable state leaks between tests | Reset state in `beforeEach` / `setUp` |
| **Sleeping in tests** | `sleep(2000)` is slow and unreliable | Use explicit waits, polling, or events |
| **Giant arrange** | 50 lines of setup obscure intent | Extract factories/builders/fixtures |
| **Assert-free tests** | Test runs but verifies nothing | Every test must assert or expect |
| **Overmocking** | Mocking everything tests nothing real | Only mock external boundaries |
| **Copy-paste tests** | Duplicated tests diverge and rot | Use parameterized tests or helpers |
| **Testing the framework** | Verifying library code works | Test *your* logic, trust dependencies |
| **Ignoring test failures** | `skip`, `xit`, `@Disabled` accumulate | Fix or delete — never hoard skipped tests |
| **Tight coupling to DB** | Tests fail when schema changes | Use repository pattern + fakes for unit tests |
| **One giant test** | Single test covers 10 scenarios | Split into focused, named tests |
| **No test for bug fix** | Regression reappears later | Every bug fix gets a regression test |

---

## NEVER Do

1. **NEVER test implementation details instead of behavior** — tests must verify what the code does, not how it does it
2. **NEVER use `sleep()` in tests** — use explicit waits, polling, events, or assertions that auto-retry
3. **NEVER share mutable state between tests** — each test sets up and tears down its own state
4. **NEVER write assert-free tests** — a test that asserts nothing proves nothing
5. **NEVER mock internal domain logic** — only mock at system boundaries (network, DB, filesystem, clock)
6. **NEVER skip tests without a linked issue and a plan to re-enable** — skipped tests rot into permanent gaps
7. **NEVER leave a test suite in a failing state** — fix it or remove it with justification before moving on
8. **NEVER chase 100% coverage as a goal** — coverage percentage is a tool, not a target; strong assertions on critical paths beat weak assertions everywhere

---

## Summary

| Do | Don't |
|----|-------|
| Test behavior, not implementation | Mock everything in sight |
| Write the test before fixing a bug | Skip tests to ship faster |
| Keep tests fast and deterministic | Use `sleep()` or shared state |
| Use factories for test data | Copy-paste setup across tests |
| Mock at system boundaries | Mock internal functions |
| Name tests descriptively | Name tests `test1`, `test2` |
| Run tests in CI on every push | Only run tests locally |
| Delete or fix skipped tests | Let `@skip` accumulate forever |
| Use parameterized tests for variants | Duplicate test code |
| Inject dependencies for testability | Hard-code dependencies |

> **Remember:** Tests are a safety net — a fast, trustworthy suite lets you refactor fearlessly and ship with confidence.

開発の人気スキル

编程大神.Skill開発

【全栈能力】编程大神.Skill:面向复杂真实项目的高阶全栈编程助手。不止生成代码,而是从一句目标接手陌生代码库,拆解需求、补齐实现、追到根因、完成重构、联调前后端,并把结果推进到能运行、能验证、能交付。覆盖 Web、后端、脚本、iOS、安卓、鸿蒙 ArkUI、微信小程序及其他技术栈,支持中英文工程、疑难 Bug、跨模块任务和长任务续做;用构建、日志、真实入口、设备或接口证据说明结果。仅问概念时直接回答,要求落地时持续推进到验收或明确阻塞。

↓ 1125.9万★ 82u_42bbb65f
编程专家Pro.Skill開発

编程专家 Pro:融合编程专家 2.0.3 工程专题与编程大神的鸿蒙 ArkTS/ArkUI、微信小程序和小游戏开发资料。用于项目实现、根因调试、审查、重构、测试、架构性能分析及多端开发验证。支持自然语言和 @专题标识,按任务读取包内知识;只问概念时直接回答。

↓ 626.9万★ 32user_47d655f0
编程专家.Skill開発

编程专家.Skill P8级编程助手,25年实战经验技能Skill,全栈:Java/Php网站/软件项目、API设计、Bug诊断、代码生成、代码审查、重构、测试用例、性能基准、技术选型、文档生成、任务拆解、Spec驱动、Karpathy规范、CMS二次开发、前端设计、MySQL/Mariadb、项目知识图谱,以及工程纪律层(根因调试硬闭环、阶段导航、事故复盘/SLO、威胁建模/供应链安全、生产就绪/渐进式发布、AI编码治理、面向Agent代码可读性、LLM应用安全)。支持 @标识 显式调用跳过路由。

↓ 600.7万★ 378user_741dc82b
dev-expert開発

编程专家.Skill P8级编程助手,25年实战经验技能Skill,全栈:Java/Php网站/软件项目、API设计、Bug诊断、代码生成、代码审查、重构、测试用例、性能基准、技术选型、文档生成、任务拆解、Spec驱动、Karpathy规范、CMS二次开发、前端设计、MySQL/Mariadb、项目知识图谱,以及工程纪律层(根因调试硬闭环、阶段导航、事故复盘/SLO、威胁建模/供应链安全、生产就绪/渐进式发布、AI编码治理、面向Agent代码可读性、LLM应用安全)。支持 @标识 显式调用跳过路由。

↓ 528.1万★ 32user_814dbe54
dev-expert-pro開発

工程专题、鸿蒙与微信小程序开发的集成派生版

↓ 104.7万★ -user_814dbe54
编程专家 Pro開発

编程专家 Pro:融合编程专家 2.0.3 工程专题与编程大神的鸿蒙 ArkTS/ArkUI、微信小程序和小游戏开发资料。用于项目实现、根因调试、审查、重构、测试、架构性能分析及多端开发验证。支持自然语言和 @专题标识,按任务读取包内知识;只问概念时直接回答。

↓ 98.2万★ 1user_28275a78
编程专家.Skill開発

适用场景:全栈编程助手。接到需求先读现有代码和约束,再动手:Java/PHP 开发、接口设计、缺陷定位、代码评审、重构、测试用例、性能排查、技术选型与文档产出,也做 CMS 二次开发、前端页面和 MySQL 调优。每次改动先给方案和影响范围,改完必须跑验证,交付附交接说明。适合要把代码真正跑通、而不是只要片段的场景。写完代码常要配套的造价、法律、工程文档,站内已有现成技能,用「查找技能」按需求找即可。

↓ 70.1万★ 6user_613b33ea
Github開発

gh コマンドラインで GitHub の PR チェック、ワークフロー実行、API 照会を扱うスキルです。

↓ 48万★ 714Peter Steinberger

wpankのその他のスキル

データ月:2026-10 · ダウンロード数とスター数は公開スキルレジストリ(ClawHub、SkillHub)から月単位で集計しています。詳しくはデータの方法論をご覧ください。