PHPUnit Testing
БесплатноБез исполняемых скриптовНе проверенComprehensive PHP testing with PHPUnit covering assertions, data providers, mocking, test doubles, database testing, and HTTP testing for reliable PHP…
от 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
- Test behavior, not implementation -- Verify what the code does from a caller's perspective, not how it achieves the result internally.
- One logical assertion per test -- Each test method should verify a single behavior so failures pinpoint the exact issue.
- Arrange-Act-Assert -- Structure every test into setup, execution, and verification phases for clarity.
- Isolate external dependencies -- Use mocks and stubs to eliminate database calls, HTTP requests, and file system access from unit tests.
- Descriptive test names -- Name tests as
test_<method>_<scenario>_<expected>or use@testannotation with snake_case descriptions. - Use data providers for parameterization -- Leverage
@dataProviderto test multiple input/output combinations without duplicating test methods. - Strict type checking -- Prefer
assertSameoverassertEqualswhen 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);
}
}
Установить 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), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic