Chuyển đến nội dung chính

第 19 課:Laravel 測試

PHPUnit,Pest 測試框架。功能測試、單元測試。資料庫測試,工廠。 HTTP 測試,模擬。瀏覽器測試(Laravel Dusk)。代碼覆蓋率。

💻 程式設計 — 第 19 課 第 19 課:Laravel 測試

Laravel:從基礎到高級

第 6 部分:測試、Docker 和生產

亞洲開發網

1.害蟲測試框架

composer require pestphp/pest --dev
php artisan pest:install
// tests/Feature/ProductTest.php
use App\Models\Product;
use App\Models\User;

test('can list products', function () {
    Product::factory()->count(5)->create();

    $response = $this->getJson('/api/products');

    $response->assertOk()
        ->assertJsonCount(5, 'data');
});

test('authenticated user can create product', function () {
    $user = User::factory()->create();

    $response = $this->actingAs($user)
        ->postJson('/api/products', [
            'name' => 'New Product',
            'slug' => 'new-product',
            'price' => 99.99,
            'category_id' => Category::factory()->create()->id,
        ]);

    $response->assertCreated();
    $this->assertDatabaseHas('products', ['name' => 'New Product']);
});

test('guest cannot create product', function () {
    $this->postJson('/api/products', [])
        ->assertUnauthorized();
});

2.HTTP測試

test('product validation', function () {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->postJson('/api/products', ['name' => ''])
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['name', 'price']);
});

test('can update product', function () {
    $product = Product::factory()->create();
    $user = User::factory()->create();

    $this->actingAs($user)
        ->putJson("/api/products/{$product->id}", ['name' => 'Updated'])
        ->assertOk();

    expect($product->fresh()->name)->toBe('Updated');
});

test('can delete product', function () {
    $product = Product::factory()->create();

    $this->actingAs(User::factory()->admin()->create())
        ->deleteJson("/api/products/{$product->id}")
        ->assertNoContent();

    $this->assertSoftDeleted('products', ['id' => $product->id]);
});

3. 嘲笑

use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;

test('order sends notification', function () {
    Notification::fake();

    $user = User::factory()->create();
    $order = Order::factory()->for($user)->create();

    Notification::assertSentTo($user, OrderShipped::class);
});

test('sends welcome email', function () {
    Mail::fake();

    $user = User::factory()->create();

    Mail::assertQueued(WelcomeMail::class, function ($mail) use ($user) {
        return $mail->hasTo($user->email);
    });
});

4. 代碼覆蓋率

php artisan test --coverage --min=80
php artisan test --parallel

下一篇: 乾淨的架構和套件。