Skip to content
acc-create-unit-test logo

Unit Test Generator

acc-create-unit-test

Generates PHPUnit unit tests for PHP 8.5. Creates isolated tests with AAA pattern, proper naming, attributes, and one behavior per test. Supports Value Objects, Entities, Services.

SKILL.md

Full skill instructions

Unit Test Generator

Generates PHPUnit 11+ unit tests for PHP 8.5 classes.

Characteristics

  • Isolated — no external dependencies (DB, HTTP, filesystem)
  • Fast — executes in <100ms
  • Focused — one behavior per test
  • AAA Pattern — Arrange-Act-Assert structure
  • Self-documenting — descriptive test names

Template

<?php

declare(strict_types=1);

namespace Tests\Unit\{Namespace};

use {FullyQualifiedClassName};
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;

#[Group('unit')]
#[CoversClass({ClassName}::class)]
final class {ClassName}Test extends TestCase
{
    private {ClassName} $sut;

    protected function setUp(): void
    {
        $this->sut = new {ClassName}(/​* dependencies */);
    }

    public function test_{method}_{scenario}_{expected}(): void
    {
        // Arrange
        {arrange_code}

        // Act
        {act_code}

        // Assert
        {assert_code}
    }
}

Naming Convention

test_{method}_{scenario}_{expected}
PartDescriptionExample
{method}Method under testcalculate_total
{scenario}Input conditionwith_discount
{expected}Expected outcomereturns_reduced_price

Examples:

test_confirm_when_pending_changes_status_to_confirmed
test_create_with_invalid_email_throws_exception
test_equals_with_same_value_returns_true
test_add_item_increases_total

Test Patterns by Component

Value Object Tests

#[Group('unit')]
#[CoversClass(Email::class)]
final class EmailTest extends TestCase
{
    // Creation - valid
    public function test_creates_with_valid_email(): void
    {
        $email = new Email('[email protected]');

        self::assertSame('[email protected]', $email->value);
    }

    // Validation - invalid
    public function test_throws_for_empty_value(): void
    {
        $this->expectException(InvalidArgumentException::class);

        new Email('');
    }

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

        new Email('not-an-email');
    }

    // Equality
    public function test_equals_returns_true_for_same_value(): void
    {
        $email1 = new Email('[email protected]');
        $email2 = new Email('[email protected]');

        self::assertTrue($email1->equals($email2));
    }

    public function test_equals_returns_false_for_different_value(): void
    {
        $email1 = new Email('[email protected]');
        $email2 = new Email('[email protected]');

        self::assertFalse($email1->equals($email2));
    }
}

Entity Tests

#[Group('unit')]
#[CoversClass(Order::class)]
final class OrderTest extends TestCase
{
    private Order $order;

    protected function setUp(): void
    {
        $this->order = new Order(
            OrderId::fromString('order-123'),
            CustomerId::fromString('customer-456')
        );
    }

    // Identity
    public function test_has_unique_identity(): void
    {
        self::assertSame('order-123', $this->order->id()->toString());
    }

    // Initial state
    public function test_is_pending_when_created(): void
    {
        self::assertTrue($this->order->isPending());
    }

    // State transitions - valid
    public function test_confirm_changes_status_to_confirmed(): void
    {
        $this->order->addItem(ProductMother::book(), 1);

        $this->order->confirm();

        self::assertTrue($this->order->isConfirmed());
    }

    // State transitions - invalid
    public function test_confirm_throws_when_already_confirmed(): void
    {
        $this->order->addItem(ProductMother::book(), 1);
        $this->order->confirm();

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

        $this->order->confirm();
    }

    // Business rules
    public function test_add_item_increases_total(): void
    {
        $this->order->addItem(ProductMother::withPrice(Money::EUR(100)), 2);

        self::assertEquals(Money::EUR(200), $this->order->total());
    }

    // Domain events
    public function test_records_order_confirmed_event(): void
    {
        $this->order->addItem(ProductMother::book(), 1);

        $this->order->confirm();

        $events = $this->order->releaseEvents();
        self::assertCount(1, $events);
        self::assertInstanceOf(OrderConfirmedEvent::class, $events[0]);
    }
}

Domain Service Tests

#[Group('unit')]
#[CoversClass(TransferMoneyService::class)]
final class TransferMoneyServiceTest extends TestCase
{
    private TransferMoneyService $service;
    private InMemoryAccountRepository $repository;
    private CollectingEventDispatcher $dispatcher;

    protected function setUp(): void
    {
        $this->repository = new InMemoryAccountRepository();
        $this->dispatcher = new CollectingEventDispatcher();
        $this->service = new TransferMoneyService(
            $this->repository,
            $this->dispatcher
        );
    }

    public function test_transfers_money_between_accounts(): void
    {
        // Arrange
        $source = AccountMother::withBalance(Money::EUR(1000));
        $target = AccountMother::withBalance(Money::EUR(500));
        $this->repository->save($source);
        $this->repository->save($target);

        // Act
        $this->service->transfer(
            $source->id(),
            $target->id(),
            Money::EUR(300)
        );

        // Assert
        $updatedSource = $this->repository->findById($source->id());
        $updatedTarget = $this->repository->findById($target->id());
        self::assertEquals(Money::EUR(700), $updatedSource->balance());
        self::assertEquals(Money::EUR(800), $updatedTarget->balance());
    }

    public function test_throws_for_insufficient_funds(): void
    {
        // Arrange
        $source = AccountMother::withBalance(Money::EUR(100));
        $target = AccountMother::withBalance(Money::EUR(500));
        $this->repository->save($source);
        $this->repository->save($target);

        // Assert
        $this->expectException(InsufficientFundsException::class);

        // Act
        $this->service->transfer(
            $source->id(),
            $target->id(),
            Money::EUR(300)
        );
    }
}

Data Providers

use PHPUnit\Framework\Attributes\DataProvider;

#[DataProvider('validEmailsProvider')]
public function test_accepts_valid_formats(string $email): void
{
    $vo = new Email($email);

    self::assertSame($email, $vo->value);
}

public static function validEmailsProvider(): array
{
    return [
        'simple' => ['[email protected]'],
        'with subdomain' => ['[email protected]'],
        'with plus' => ['[email protected]'],
        'with dots' => ['[email protected]'],
    ];
}

#[DataProvider('invalidEmailsProvider')]
public function test_rejects_invalid_formats(string $email): void
{
    $this->expectException(InvalidArgumentException::class);

    new Email($email);
}

public static function invalidEmailsProvider(): array
{
    return [
        'empty' => [''],
        'no at' => ['userexample.com'],
        'no domain' => ['user@'],
        'spaces' => ['user @example.com'],
    ];
}

Generation Instructions

  1. Analyze the class:

    • Identify public methods
    • Identify dependencies (constructor parameters)
    • Identify value objects (final readonly)
    • Identify entities (has id, state changes)
    • Identify services (orchestrates, uses repositories)
  2. Determine test cases:

    • Happy path for each method
    • Edge cases (null, empty, boundary)
    • Exception paths (validation failures)
    • State transitions (for entities)
  3. Generate test class:

    • Match namespace: src/​Domain/​Order/​Order.php → tests/​Unit/​Domain/​Order/​OrderTest.php
    • Add attributes: #[Group('unit')], #[CoversClass]
    • Create setUp if shared state needed
  4. Generate test methods:

    • Follow naming convention
    • Use AAA structure
    • One assertion group per test
  5. Add helpers if needed:

    • Use existing Mothers/​Builders
    • Create inline builders for simple cases

Assertions Reference

// Value comparisons
self::assertSame($expected, $actual);      // ===
self::assertEquals($expected, $actual);    // ==
self::assertTrue($condition);
self::assertFalse($condition);
self::assertNull($value);
self::assertNotNull($value);

// Types
self::assertInstanceOf(ClassName::class, $object);

// Strings
self::assertStringContainsString($needle, $haystack);
self::assertStringStartsWith($prefix, $string);

// Arrays
self::assertCount($expected, $array);
self::assertContains($needle, $array);
self::assertArrayHasKey($key, $array);

// Exceptions
$this->expectException(ExceptionClass::class);
$this->expectExceptionMessage('message');
$this->expectExceptionCode(404);

Usage

Provide:

  • Path to class to test
  • Or class name and namespace
  • Specific methods to focus on (optional)

The generator will:

  1. Read the source class
  2. Analyze methods and dependencies
  3. Generate comprehensive test class
  4. Include happy path + edge cases + exceptions

More skills from diegosouzapw

accessibility logo
diegosouzapw/awesome-omni-skill

accessibility

Accessibility guidelines for VS Code features — covers accessibility help dialogs, accessible views, verbosity settings, accessibility signals, ARIA alerts/status announcements, keyboard navigation, and ARIA labels/roles. Applies to both new interactive UI surfaces and updates to existing feature...

62 1
View
mermaid-diagrams logo
diegosouzapw/awesome-omni-skill

mermaid-diagrams

Mermaid diagram creation for flowcharts, sequences, ERDs, and more. Generate diagrams from text in markdown files. Use for documentation, architecture diagrams, and visual representations. Triggers on mermaid, flowchart, sequence diagram, ERD, entity relationship, gantt chart, pie chart, class di...

62 1
View
tauri2-react-rust logo
diegosouzapw/awesome-omni-skill

tauri2-react-rust

Guides development of cross-platform desktop apps with Tauri 2, TypeScript, React, and Rust. Use when building Tauri apps, implementing IPC, designing Rust backend or TypeScript/React frontend, when researching or cloning a website (open site, snapshot elements), when verifying local dev or built...

62 1
View
fp-ts-errors logo
diegosouzapw/awesome-omni-skill

fp-ts-errors

Handle errors as values using fp-ts Either and TaskEither for cleaner, more predictable TypeScript code. Use when implementing error handling patterns with fp-ts.

62 0
View
ring:pre-dev-research logo
diegosouzapw/awesome-omni-skill

ring:pre-dev-research

Gate 0 research phase for pre-dev workflow. Dispatches 3 parallel research agents to gather codebase patterns, external best practices, and framework documentation BEFORE creating PRD/TRD. Outputs research.md with file:line references.

62 0
View
create-assistant logo
diegosouzapw/awesome-omni-skill

create-assistant

Create and configure Vapi voice AI assistants with models, voices, transcribers, tools, hooks, and advanced settings. Use when building voice agents, phone bots, customer support assistants, or any conversational AI that handles phone or web calls.

62 0
View
codex-headless logo
diegosouzapw/awesome-omni-skill

codex-headless

Delegiere Aufgaben an OpenAI Codex CLI im Headless-Mode. Nutzt ChatGPT Subscription (KEIN API Key). Nur Workspace-Zugriff, KEIN System-Zugriff. Auto-Accept mit --full-auto. Web-Recherche mit --search.

62 0
View
social-media-scheduler logo
diegosouzapw/awesome-omni-skill

social-media-scheduler

Generate a full week of social media content for any topic. Outputs platform-optimized posts for Twitter/X, LinkedIn, and Instagram with hashtags and posting times.

62 0
View
Data Privacy Compliance logo
diegosouzapw/awesome-omni-skill

Data Privacy Compliance

Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws. Use when implementing privacy controls, conducting data protection impact assessments, ensuring regulatory compliance, or managing data subject rights. Expert in consent management, da...

62 0
View
triple-review logo
diegosouzapw/awesome-omni-skill

triple-review

Reviews a task using the TRIPLE protocol, as the review agent.

62 0
View
Tech Stack & Architecture Decision logo
diegosouzapw/awesome-omni-skill

Tech Stack & Architecture Decision

Define and document the technology stack and architecture decisions for a project. Use when the user needs to choose a tech stack, make architecture decisions, define infrastructure choices, or document technology selections. Triggers on requests like "define the tech stack", "choose technologies...

62 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View