testing-knowledge

为 PHP 8.4 项目提供测试知识库,涵盖测试金字塔、AAA 模式、命名规范、隔离原则、领域驱动设计的测试指南以及 PHPUnit 的常见模式。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "testing-knowledge":https://skillpi.com/zh/skills/deepskill-980e7334e5a4c0b60e89136e4a9b66ba43a09ec049811239acdc624aaa8592e9。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

为 PHP 8.4 项目提供测试知识库,涵盖测试金字塔、AAA 模式、命名规范、隔离原则、领域驱动设计的测试指南以及 PHPUnit 的常见模式。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: testing-knowledge
description: Testing knowledge base for PHP 8.4 projects. Provides testing pyramid, AAA pattern, naming conventions, isolation principles, DDD testing guidelines, and PHPUnit patterns.

Testing Knowledge Base

Quick reference for PHP testing patterns, principles, and best practices.

Testing Pyramid

        /\
       /  \     Functional (10%)
      /────\    - E2E, browser tests
     /      \   - Slow, fragile
    /────────\  Integration (20%)
   /          \ - DB, HTTP, queues
  /────────────\Unit (70%)
 /              \- Fast, isolated
/________________\- Business logic

Rule: 70% unit, 20% integration, 10% functional. Invert the pyramid = slow, brittle test suite.

AAA Pattern (Arrange-Act-Assert)

public function test_order_calculates_total_with_discount(): void
{
    // Arrange — set up test data
    $order = new Order(OrderId::generate());
    $order->addItem(new Product('Book', Money::EUR(100)));
    $discount = new PercentageDiscount(10);

    // Act — execute the behavior
    $total = $order->calculateTotal($discount);

    // Assert — verify the outcome
    self::assertEquals(Money::EUR(90), $total);
}

Rules:

  • One blank line between sections
  • Single Act per test
  • Assert behavior, not implementation

Naming Conventions

PHPUnit Style

test_{method}_{scenario}_{expected}
Example Method Scenario Expected
test_calculate_total_with_discount_returns_reduced_amount calculateTotal with discount returns reduced amount
test_confirm_when_already_shipped_throws_exception confirm when already shipped throws exception
test_email_with_invalid_format_fails_validation Email (VO) with invalid format fails validation

Pest Style

it('calculates total with discount applied')
it('throws exception when confirming shipped order')
it('fails validation for invalid email format')

Test Isolation Principles

DO

  • [ ] Fresh fixtures per test
  • [ ] Independent test execution (any order)
  • [ ] Teardown cleans all state
  • [ ] Use in-memory implementations

DON'T

  • [ ] Shared mutable state between tests
  • [ ] Tests depending on execution order
  • [ ] Global variables or singletons
  • [ ] Real external services in unit tests

Quick Quality Checklist

Rule Check
One test = one behavior Single assertion group
Test is documentation Name reads as specification
No logic in tests No if/for/while
Fast execution <100ms per unit test
Mock interfaces only Never mock VO, Entity, final
≤3 mocks per test More = design smell
Behavior over implementation Test WHAT, not HOW

DDD Component Testing

Component Test Focus Mocks Allowed
Value Object Validation, equality, immutability None
Entity State transitions, business rules None
Aggregate Invariants, consistency, events None
Domain Service Business logic spanning aggregates Repository (Fake)
Application Service Orchestration, transactions Repository, EventDispatcher
Repository CRUD operations Database (SQLite)

PHP 8.4 Test Patterns

Unit Test Template

<?php

declare(strict_types=1);

namespace Tests\Unit\Domain;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;

#[Group('unit')]
#[CoversClass(Email::class)]
final class EmailTest extends TestCase
{
    public function test_creates_valid_email(): void
    {
        $email = new Email('user@example.com');

        self::assertSame('user@example.com', $email->value);
    }

    public function test_throws_for_invalid_format(): void
    {
        $this->expectException(InvalidArgumentException::class);

        new Email('invalid');
    }
}

Integration Test Template

<?php

declare(strict_types=1);

namespace Tests\Integration\Infrastructure;

use PHPUnit\Framework\Attributes\Group;
use Tests\DatabaseTestCase;

#[Group('integration')]
final class DoctrineOrderRepositoryTest extends DatabaseTestCase
{
    private OrderRepositoryInterface $repository;

    protected function setUp(): void
    {
        parent::setUp();
        $this->repository = $this->getContainer()->get(OrderRepositoryInterface::class);
    }

    public function test_saves_and_retrieves_order(): void
    {
        // Arrange
        $order = OrderMother::pending();

        // Act
        $this->repository->save($order);
        $found = $this->repository->findById($order->id());

        // Assert
        self::assertNotNull($found);
        self::assertTrue($order->id()->equals($found->id()));
    }
}

Test Doubles Quick Reference

Type Purpose When to Use
Stub Returns canned answers External API responses
Mock Verifies interactions Event publishing
Fake Working implementation InMemory repository
Spy Records calls Logging, notifications

Decision Matrix

Need to verify a call was made?
├── Yes → Mock or Spy
└── No → Need real behavior?
    ├── Yes → Fake
    └── No → Stub

Common Test Smells

Smell Detection Fix
Logic in Test if, for, while in test Extract to helper or parameterize
Mock Overuse >3 mocks Refactor design, use Fakes
Mystery Guest External files, hidden data Inline test data or use Builder
Eager Test Tests multiple behaviors Split into separate tests
Fragile Test Breaks on refactor Test behavior, not implementation

Advanced Testing Patterns

Contract Testing (Pact)

Aspect Unit Test Integration Test Contract Test
Speed Fast Slow Medium
Scope Single class Service + deps API boundary
Isolation Full Partial Consumer/Provider
Use case Business logic DB, queues Service-to-service

When to use: Microservices REST APIs, message-based systems, event schema verification.

Load Testing Patterns

Pattern Duration Load Profile Goal
Smoke 1-2 min Minimal Verify script works
Load 10-30 min Expected traffic Performance baseline
Stress 10-30 min 1.5-2x expected Find breaking point
Spike 5-10 min Sudden burst Test auto-scaling
Soak 2-8 hours Sustained Find memory leaks

Chaos Testing (Failure Injection)

Failure How to Inject What It Tests
Network latency Sleep in middleware Timeout handling
Service error Return 500 randomly Circuit breaker
Connection refused Close port Fallback behavior
Slow database Query delay Query timeout handling

E2E Distributed Testing

Strategy How Trade-off
Test containers Docker Compose per test Isolated but slow
Shared staging Dedicated environment Fast but interference
Data seeding API/DB setup per test Controlled but complex
Snapshot restore DB snapshot before tests Fast reset

References

For detailed information, load these reference files:

  • references/unit-testing.md — Unit test patterns and examples
  • references/integration-testing.md — Integration test setup and patterns
  • references/ddd-testing.md — Testing DDD components (VO, Entity, Aggregate, Service)
  • references/advanced-testing.md — Contract testing (Pact), chaos testing, load testing patterns (ramp-up, spike, soak), E2E distributed testing

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值88/100

亮点

  • 提供 PHP 8.4 项目全面的测试知识体系,涵盖从基础到高级的测试模式
  • 内容结构清晰,包含测试金字塔、AAA 模式、DDD 测试指南等核心概念
  • 面向开发者实际痛点,具有明确的实用价值和广泛受众
触发精准95/100

亮点

  • 触发描述精准完整,覆盖 PHP 测试相关核心概念
  • description 位于正确位置且内容无截断
结构规范92/100

亮点

  • 文档结构清晰,分章节组织,每部分有明确标题和示例
  • 包含端到端代码模板和决策矩阵,便于直接落地
  • frontmatter 完整,单文件长度合理
执行可靠90/100

待提升项

  • 引用文件缺失 原报告严重程度:重大

    SKILL.md 中引用了 references/unit-testing.md、references/integration-testing.md、references/ddd-testing.md、references/advanced-testing.md 文件,但未传入这些文件

    改进建议:请补充 references/ 目录下被引用的所有文件,或移除对这些文件的引用

亮点

  • 内容基于 PHP 8.4 和 PHPUnit 标准,参数和模式正确
  • 覆盖主要异常场景和测试坏味道,提供修复建议
证据可验 (前四项均值)91/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。