Laravel Testing
Agent Workflow (MANDATORY)
Before ANY implementation, spawn 3 agents in parallel, one Agent call each with a name:
- fuse-ai-pilot:explore-codebase - Analyze existing test patterns
- fuse-ai-pilot:research-expert - Verify Pest/PHPUnit docs via Context7
- mcp__context7__query-docs - Check assertion and mocking patterns
After implementation, run fuse-ai-pilot:sniper for validation.
Overview
| Type |
Purpose |
Location |
| Feature |
HTTP, full stack |
tests/Feature/ |
| Unit |
Isolated classes |
tests/Unit/ |
| Arch |
Code architecture |
tests/Arch.php |
Decision Guide: Test Type
What to test?
├── HTTP endpoint → Feature test
├── Service/Policy logic → Unit test
├── Code structure → Arch test
├── External API → Mock with Http::fake()
├── Mail/Queue/Event → Use Fakes
└── Database state → assertDatabaseHas()
Decision Guide: Test Strategy
Coverage strategy?
├── Feature tests (70%) → Critical flows
├── Unit tests (25%) → Business logic
├── E2E tests (5%) → User journeys
└── Arch tests → Structural rules
Critical Rules
- Use RefreshDatabase for database isolation
- Use factories for test data (never raw inserts)
- Mock external services - Never call real APIs
- Test edge cases - Empty, null, boundaries
- Run parallel -
pest --parallel for speed
Reference Guide
Pest Basics
| Topic |
Reference |
When to Consult |
| Pest Syntax |
pest-basics.md |
it(), test(), describe() |
| Datasets |
pest-datasets.md |
Data providers, hooks |
| Architecture |
pest-arch.md |
arch() tests |
HTTP Testing
| Topic |
Reference |
When to Consult |
| Requests |
http-requests.md |
GET, POST, headers |
| JSON API |
http-json.md |
API assertions |
| Authentication |
http-auth.md |
actingAs, guards |
| Assertions |
http-assertions.md |
Status, redirects |
Database Testing
| Topic |
Reference |
When to Consult |
| Basics |
database-basics.md |
RefreshDatabase |
| Factories |
database-factories.md |
Factory patterns |
| Assertions |
database-assertions.md |
DB assertions |
Mocking
| Topic |
Reference |
When to Consult |
| Services |
mocking-services.md |
Mock, spy |
| Fakes |
mocking-fakes.md |
Mail, Queue, Event |
| HTTP & Time |
mocking-http.md |
Http::fake, travel |
Other
| Topic |
Reference |
When to Consult |
| Console |
console-tests.md |
Artisan tests |
| Troubleshooting |
troubleshooting.md |
Common errors |
Templates
| Template |
When to Use |
| FeatureTest.php.md |
HTTP feature test |
| UnitTest.php.md |
Service unit test |
| ArchTest.php.md |
Architecture test |
| ApiTest.php.md |
REST API test |
| PestConfig.php.md |
Pest configuration |
Quick Reference
// Feature test
it('creates a post', function () {
$user = User::factory()->create();
$this->actingAs($user)
->postJson('/api/posts', ['title' => 'Test'])
->assertCreated()
->assertJsonPath('data.title', 'Test');
$this->assertDatabaseHas('posts', ['title' => 'Test']);
});
// With dataset
it('validates emails', function (string $email, bool $valid) {
// test logic
})->with([
['valid@test.com', true],
['invalid', false],
]);
// Mock facade
Mail::fake();
// ... action ...
Mail::assertSent(OrderShipped::class);
Commands
# Run all tests
php artisan test
# Pest directly
./vendor/bin/pest
# Parallel execution
./vendor/bin/pest --parallel
# Filter by name
./vendor/bin/pest --filter "user can"
# Coverage
./vendor/bin/pest --coverage --min=80
# Profile slow tests
./vendor/bin/pest --profile
Best Practices
DO
- Use
RefreshDatabase trait
- Follow AAA pattern (Arrange-Act-Assert)
- Name tests descriptively
- Test one thing per test
- Use factories for data
DON'T
- Create test dependencies
- Call real external APIs
- Use production database
- Skip edge cases
Laravel 13 Notes
PHPUnit 12 + Pest 4
Laravel 13 requires PHPUnit 12 and supports Pest 4. PHP attributes replace docblock annotations.
use PHPUnit\Framework\Attributes\Test;
use Illuminate\Foundation\Testing\Attributes\Seed;
use Illuminate\Foundation\Testing\Attributes\Seeder;
#[Seed] // runs DatabaseSeeder
#[Seeder(UserSeeder::class)] // runs a targeted seeder
final class UserTest extends TestCase
{
#[Test]
public function it_creates_user(): void { /* ... */ }
}
Str cache reset
Laravel 13 automatically resets Str caches (random, slug) between tests to avoid state leak. No manual setup required.
Migration from Pest 3
pest --init regenerates Pest.php with the new API
- Datasets now support native PHP generators
expect()->toBeInstanceOf() → strict typing required
1---2name: laravel-testing3description: Use when testing controllers, services, or models, or implementing TDD on Laravel 13 with Pest 4 / PHPUnit 12.4versions:5 laravel: "13.0"6 pest: "4.0"7 phpunit: "12.0"8 php: "8.3"9user-invocable: false10references: references/pest-basics.md, references/pest-datasets.md, references/pest-arch.md, references/http-requests.md, references/http-json.md, references/http-auth.md, references/http-assertions.md, references/database-basics.md, references/database-factories.md, references/database-assertions.md, references/mocking-services.md, references/mocking-fakes.md, references/mocking-http.md, references/console-tests.md, references/troubleshooting.md, references/templates/FeatureTest.php.md, references/templates/UnitTest.php.md, references/templates/ArchTest.php.md, references/templates/ApiTest.php.md, references/templates/PestConfig.php.md11related-skills: laravel-architecture, laravel-eloquent12metadata:13 source: https://skillmd.com/skills/fusengine/laravel-testing14---1516<objective>17Covers Laravel 13 testing with Pest 4 and PHPUnit 12: feature tests (HTTP,18full stack), unit tests (isolated classes), and architecture tests; Pest19syntax (it/test/describe), datasets; HTTP testing (requests, JSON20assertions, auth/actingAs, status/redirect assertions); database testing21(RefreshDatabase, factories, DB assertions); mocking (services, spies,22Mail/Queue/Event fakes, Http::fake, time travel); console/Artisan command23tests; and PHPUnit-attribute-based seeding (#[Seed], #[Seeder]).24</objective>2526# Laravel Testing2728## Agent Workflow (MANDATORY)2930Before ANY implementation, spawn 3 agents in parallel, one `Agent` call each with a `name`:31321. **fuse-ai-pilot:explore-codebase** - Analyze existing test patterns332. **fuse-ai-pilot:research-expert** - Verify Pest/PHPUnit docs via Context7343. **mcp__context7__query-docs** - Check assertion and mocking patterns3536After implementation, run **fuse-ai-pilot:sniper** for validation.3738---3940## Overview4142| Type | Purpose | Location |43|------|---------|----------|44| **Feature** | HTTP, full stack | `tests/Feature/` |45| **Unit** | Isolated classes | `tests/Unit/` |46| **Arch** | Code architecture | `tests/Arch.php` |4748---4950## Decision Guide: Test Type5152```53What to test?54├── HTTP endpoint → Feature test55├── Service/Policy logic → Unit test56├── Code structure → Arch test57├── External API → Mock with Http::fake()58├── Mail/Queue/Event → Use Fakes59└── Database state → assertDatabaseHas()60```6162---6364## Decision Guide: Test Strategy6566```67Coverage strategy?68├── Feature tests (70%) → Critical flows69├── Unit tests (25%) → Business logic70├── E2E tests (5%) → User journeys71└── Arch tests → Structural rules72```7374---7576## Critical Rules77781. **Use RefreshDatabase** for database isolation792. **Use factories** for test data (never raw inserts)803. **Mock external services** - Never call real APIs814. **Test edge cases** - Empty, null, boundaries825. **Run parallel** - `pest --parallel` for speed8384---8586## Reference Guide8788### Pest Basics8990| Topic | Reference | When to Consult |91|-------|-----------|-----------------|92| **Pest Syntax** | [pest-basics.md](references/pest-basics.md) | it(), test(), describe() |93| **Datasets** | [pest-datasets.md](references/pest-datasets.md) | Data providers, hooks |94| **Architecture** | [pest-arch.md](references/pest-arch.md) | arch() tests |9596### HTTP Testing9798| Topic | Reference | When to Consult |99|-------|-----------|-----------------|100| **Requests** | [http-requests.md](references/http-requests.md) | GET, POST, headers |101| **JSON API** | [http-json.md](references/http-json.md) | API assertions |102| **Authentication** | [http-auth.md](references/http-auth.md) | actingAs, guards |103| **Assertions** | [http-assertions.md](references/http-assertions.md) | Status, redirects |104105### Database Testing106107| Topic | Reference | When to Consult |108|-------|-----------|-----------------|109| **Basics** | [database-basics.md](references/database-basics.md) | RefreshDatabase |110| **Factories** | [database-factories.md](references/database-factories.md) | Factory patterns |111| **Assertions** | [database-assertions.md](references/database-assertions.md) | DB assertions |112113### Mocking114115| Topic | Reference | When to Consult |116|-------|-----------|-----------------|117| **Services** | [mocking-services.md](references/mocking-services.md) | Mock, spy |118| **Fakes** | [mocking-fakes.md](references/mocking-fakes.md) | Mail, Queue, Event |119| **HTTP & Time** | [mocking-http.md](references/mocking-http.md) | Http::fake, travel |120121### Other122123| Topic | Reference | When to Consult |124|-------|-----------|-----------------|125| **Console** | [console-tests.md](references/console-tests.md) | Artisan tests |126| **Troubleshooting** | [troubleshooting.md](references/troubleshooting.md) | Common errors |127128### Templates129130| Template | When to Use |131|----------|-------------|132| [FeatureTest.php.md](references/templates/FeatureTest.php.md) | HTTP feature test |133| [UnitTest.php.md](references/templates/UnitTest.php.md) | Service unit test |134| [ArchTest.php.md](references/templates/ArchTest.php.md) | Architecture test |135| [ApiTest.php.md](references/templates/ApiTest.php.md) | REST API test |136| [PestConfig.php.md](references/templates/PestConfig.php.md) | Pest configuration |137138---139140## Quick Reference141142```php143// Feature test144it('creates a post', function () {145 $user = User::factory()->create();146147 $this->actingAs($user)148 ->postJson('/api/posts', ['title' => 'Test'])149 ->assertCreated()150 ->assertJsonPath('data.title', 'Test');151152 $this->assertDatabaseHas('posts', ['title' => 'Test']);153});154155// With dataset156it('validates emails', function (string $email, bool $valid) {157 // test logic158})->with([159 ['valid@test.com', true],160 ['invalid', false],161]);162163// Mock facade164Mail::fake();165// ... action ...166Mail::assertSent(OrderShipped::class);167```168169---170171## Commands172173```bash174# Run all tests175php artisan test176177# Pest directly178./vendor/bin/pest179180# Parallel execution181./vendor/bin/pest --parallel182183# Filter by name184./vendor/bin/pest --filter "user can"185186# Coverage187./vendor/bin/pest --coverage --min=80188189# Profile slow tests190./vendor/bin/pest --profile191```192193---194195## Best Practices196197### DO198- Use `RefreshDatabase` trait199- Follow AAA pattern (Arrange-Act-Assert)200- Name tests descriptively201- Test one thing per test202- Use factories for data203204### DON'T205- Create test dependencies206- Call real external APIs207- Use production database208- Skip edge cases209210---211212## Laravel 13 Notes213214### PHPUnit 12 + Pest 4215Laravel 13 requires **PHPUnit 12** and supports **Pest 4**. PHP attributes replace docblock annotations.216217```php218use PHPUnit\Framework\Attributes\Test;219use Illuminate\Foundation\Testing\Attributes\Seed;220use Illuminate\Foundation\Testing\Attributes\Seeder;221222#[Seed] // runs DatabaseSeeder223#[Seeder(UserSeeder::class)] // runs a targeted seeder224final class UserTest extends TestCase225{226 #[Test]227 public function it_creates_user(): void { /* ... */ }228}229```230231### Str cache reset232Laravel 13 automatically resets `Str` caches (random, slug) between tests to avoid state leak. No manual setup required.233234### Migration from Pest 3235- `pest --init` regenerates `Pest.php` with the new API236- Datasets now support native PHP generators237- `expect()->toBeInstanceOf()` → strict typing required