GlosarioTesting

¿Qué es PHPUnit?

PHPUnit es el framework de testing unitario estandar para PHP que Laravel integra de serie, permitiendo escribir tests de unidad, integracion y funcionales con assertions, mocks y data providers.

PHPUnit

PHPUnit es el framework de testing estandar de PHP y viene integrado en Laravel desde siempre. Aunque Pest es ahora la opcion recomendada, PHPUnit sigue siendo completamente soportado.

Escribir tests

// tests/Feature/PostTest.php
class PostTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_create_post(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)
            ->post('/posts', [
                'title' => 'Test Post',
                'body' => 'Contenido de prueba',
            ]);

        $response->assertRedirect('/posts');
        $this->assertDatabaseHas('posts', [
            'title' => 'Test Post',
            'user_id' => $user->id,
        ]);
    }

    public function test_guest_cannot_create_post(): void
    {
        $this->post('/posts', ['title' => 'Test'])
            ->assertRedirect('/login');
    }
}

Tests de unidad

class SlugGeneratorTest extends TestCase
{
    public function test_generates_slug_from_title(): void
    {
        $generator = new SlugGenerator();

        $this->assertEquals('hola-mundo', $generator->generate('Hola Mundo'));
        $this->assertEquals('laravel-es-genial', $generator->generate('Laravel es genial'));
    }
}

Laravel proporciona traits como RefreshDatabase, WithFaker y DatabaseTransactions que simplifican enormemente la preparacion del entorno de pruebas. PHPUnit se configura en phpunit.xml.