Skill: Write Tests

Skill: Write Tests

Unit Test for Aggregate

declare(strict_types=1);

namespace App\Tests\Unit\Module\{Module}\Domain\Model;

use PHPUnit\Framework\TestCase;

final class {Aggregate}Test extends TestCase
{
    public function test_create_with_valid_data(): void
    {
        $aggregate = {Aggregate}::create(
            id: new {Aggregate}Id('uuid-here'),
            tenantId: new TenantId('tenant-uuid'),
            // ... valid params
        );

        $this->assertSame('uuid-here', $aggregate->id()->value);
        // Assert other properties

        $events = $aggregate->releaseEvents();
        $this->assertCount(1, $events);
        $this->assertInstanceOf({Aggregate}Created::class, $events[0]);
    }

    public function test_create_without_required_field_throws(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        // ... test invariant violation
    }
}

Unit Test for Command Handler

final class Create{Entity}CommandHandlerTest extends TestCase
{
    public function test_creates_{entity}_and_persists(): void
    {
        $repository = $this->createMock({Aggregate}RepositoryInterface::class);
        $repository->expects($this->once())->method('save');

        $handler = new Create{Entity}CommandHandler($repository);
        $handler(new Create{Entity}Command(/* ... */));
    }
}

Integration Test for API Endpoint

final class {Entity}ControllerTest extends WebTestCase
{
    public function test_list_{entities}_returns_200(): void
    {
        $client = static::createClient();
        // ... setup auth + fixtures

        $client->request('GET', '/api/v1/{entities}');

        $this->assertResponseStatusCodeSame(200);
        $data = json_decode($client->getResponse()->getContent(), true);
        $this->assertArrayHasKey('data', $data);
    }

    public function test_create_{entity}_returns_201(): void
    {
        $client = static::createClient();
        // ... setup auth

        $client->request('POST', '/api/v1/{entities}', [], [], [
            'CONTENT_TYPE' => 'application/json',
        ], json_encode([/* valid payload */]));

        $this->assertResponseStatusCodeSame(201);
    }

    public function test_create_{entity}_without_auth_returns_401(): void
    {
        $client = static::createClient();
        $client->request('POST', '/api/v1/{entities}');

        $this->assertResponseStatusCodeSame(401);
    }
}