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
次の記事: クリーンなアーキテクチャとパッケージ。