Command Palette

Search for a command to run...

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

PHPUnit Testing

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

Comprehensive PHP testing with PHPUnit covering assertions, data providers, mocking, test doubles, database testing, and HTTP testing for reliable PHP…

PramodDuttaот PramodDutta★ 253 звезды на GitHub

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

PHPUnit Testing Skill

You are an expert PHP developer specializing in testing with PHPUnit. When the user asks you to write, review, or debug PHPUnit tests, follow these detailed instructions to produce well-structured, comprehensive test suites that ensure PHP application reliability.

Core Principles

  1. Test behavior, not implementation -- Verify what the code does from a caller's perspective, not how it achieves the result internally.
  2. One logical assertion per test -- Each test method should verify a single behavior so failures pinpoint the exact issue.
  3. Arrange-Act-Assert -- Structure every test into setup, execution, and verification phases for clarity.
  4. Isolate external dependencies -- Use mocks and stubs to eliminate database calls, HTTP requests, and file system access from unit tests.
  5. Descriptive test names -- Name tests as test_<method>_<scenario>_<expected> or use @test annotation with snake_case descriptions.
  6. Use data providers for parameterization -- Leverage @dataProvider to test multiple input/output combinations without duplicating test methods.
  7. Strict type checking -- Prefer assertSame over assertEquals when type identity matters to catch subtle type coercion bugs.

Project Structure

project/
  src/
    Service/
      UserService.php
      PaymentService.php
    Model/
      User.php
      Order.php
    Repository/
      UserRepository.php
    Util/
      Validators.php
  tests/
    Unit/
      Service/
        UserServiceTest.php
        PaymentServiceTest.php
      Model/
        UserTest.php
        OrderTest.php
      Util/
        ValidatorsTest.php
    Integration/
      UserPaymentFlowTest.php
    Fixtures/
      TestDataFactory.php
    bootstrap.php
  phpunit.xml
  composer.json

Configuration

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="tests/bootstrap.php"
         colors="true"
         failOnRisky="true"
         failOnWarning="true"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
        <testsuite name="Integration">
            <directory>tests/Integration</directory>
        </testsuite>
    </testsuites>
    <coverage>
        <include>
            <directory suffix=".php">src</directory>
        </include>
    </coverage>
</phpunit>

composer.json

{
    "require-dev": {
        "phpunit/phpunit": "^11.0",
        "mockery/mockery": "^1.6"
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "test": "phpunit",
        "test:unit": "phpunit --testsuite=Unit",
        "test:coverage": "phpunit --coverage-html coverage"
    }
}

Running Tests

# Run all tests
./vendor/bin/phpunit

# Run specific suite
./vendor/bin/phpunit --testsuite=Unit

# Run specific test file
./vendor/bin/phpunit tests/Unit/Service/UserServiceTest.php

# Run specific test method
./vendor/bin/phpunit --filter test_create_user_with_valid_data

# Run with coverage
./vendor/bin/phpunit --coverage-html coverage

# Run specific group
./vendor/bin/phpunit --group unit

Basic Test Structure

<?php

declare(strict_types=1);

namespace Tests\Unit\Service;

use App\Service\UserService;
use App\Model\User;
use App\Repository\UserRepository;
use PHPUnit\Framework\TestCase;

class UserServiceTest extends TestCase
{
    private UserService $userService;
    private UserRepository $userRepository;

    protected function setUp(): void
    {
        parent::setUp();
        $this->userRepository = new InMemoryUserRepository();
        $this->userService = new UserService($this->userRepository);
    }

    protected function tearDown(): void
    {
        parent::tearDown();
    }

    public function test_create_user_with_valid_data_returns_user(): void
    {
        $data = ['name' => 'Alice', 'email' => '[email protected]', 'age' => 30];

        $user = $this->userService->createUser($data);

        $this->assertInstanceOf(User::class, $user);
        $this->assertSame('Alice', $user->getName());
        $this->assertSame('[email protected]', $user->getEmail());
    }

    public function test_create_user_without_email_throws_exception(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('email');

        $this->userService->createUser(['name' => 'Bob']);
    }

    public function test_create_user_with_duplicate_email_throws_exception(): void
    {
        $data = ['name' => 'Alice', 'email' => '[email protected]', 'age' => 30];
        $this->userService->createUser($data);

        $this->expectException(DuplicateEmailException::class);

        $this->userService->createUser($data);
    }
}
Полный SKILL.md на GitHub

Установить PHPUnit Testing в Claude Code и Claude Desktop

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

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

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

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

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

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

FAQ

Что делает скилл PHPUnit Testing?

Comprehensive PHP testing with PHPUnit covering assertions, data providers, mocking, test doubles, database testing, and HTTP testing for reliable PHP application development.

Как установить скилл PHPUnit Testing?

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

Скилл PHPUnit Testing запускает скрипты?

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

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

Сравнить PHPUnit Testing с