Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Testbench Laravel Package

orchestra/testbench

Orchestra Testbench is the de facto helper for testing Laravel packages. It boots a lightweight Laravel app for PHPUnit/Pest, so you can run integration and feature tests against your package with minimal setup and fast feedback.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require --dev orchestra/testbench

Add to your composer.json under require-dev:

"orchestra/testbench": "^11.0"
  1. Basic Test Class: Extend Orchestra\Testbench\TestCase in your test file:

    use Orchestra\Testbench\TestCase;
    
    class ExampleTest extends TestCase
    {
        public function test_basic()
        {
            $this->assertTrue(true);
        }
    }
    
  2. First Use Case: Load your package and its providers in getPackageProviders():

    protected function getPackageProviders($app)
    {
        return [
            \YourVendor\YourPackage\YourPackageServiceProvider::class,
        ];
    }
    
  3. Run Tests:

    phpunit
    

Key Starting Points

  • Official Documentation (covers setup, providers, migrations, etc.)
  • testbench.yaml configuration (for customizing test environments)
  • Concerns\WithFixtures for database seeding

Implementation Patterns

Core Workflows

1. Package Provider Registration

protected function getPackageProviders($app)
{
    return [
        \YourVendor\YourPackage\Providers\AuthServiceProvider::class,
        \YourVendor\YourPackage\Providers\RouteServiceProvider::class,
    ];
}
  • Tip: Use getPackageAliases() for facade aliases if needed.

2. Database Testing

  • Migrations:
    $this->loadMigrationsFrom([
        __DIR__.'/../database/migrations',
        __DIR__.'/../../vendor/your-package/src/database/migrations',
    ]);
    
  • Seeders (via testbench.yaml):
    seeders: true
    
    Or programmatically:
    $this->artisan('db:seed', ['--class' => 'YourSeeder']);
    

3. Mocking and Stubbing

  • Mockery Integration (built-in):
    $mock = Mockery::mock('alias:YourContract');
    $mock->shouldReceive('method')->once();
    $this->app->instance('YourContract', $mock);
    
  • Service Container Binding:
    $this->app->bind('YourInterface', function () {
        return new YourImplementation();
    });
    

4. HTTP Testing

  • Route Testing:
    $response = $this->get('/your-package/endpoint');
    $response->assertStatus(200);
    
  • Middleware:
    $this->app->middleware('your.package.middleware');
    

5. Custom Test Environments

  • testbench.yaml:
    skeleton: custom/path/to/skeleton
    environment: testing
    seeders: true
    
  • Dynamic Environment Setup:
    $this->withEnvironmentSetup([
        'APP_DEBUG' => true,
        'YOUR_PACKAGE_OPTION' => 'value',
    ]);
    

6. Fixtures with WithFixtures

use Orchestra\Testbench\Concerns\WithFixtures;

class UserTest extends TestCase
{
    use WithFixtures;

    protected function getFixturesPath()
    {
        return __DIR__.'/fixtures';
    }
}
  • Fixtures are loaded automatically before each test.

7. Parallel Testing

  • Ensure WithFixtures is compatible with --parallel flag in PHPUnit:
    phpunit --parallel
    
  • Use terminate() or bail() for early exits in parallel tests:
    if ($this->shouldSkip()) {
        Orchestra\Testbench\bail('Skipping test...');
    }
    

Integration Tips

1. Testing Package Commands

$this->artisan('your-package:command')
     ->expectsQuestion('confirm', 'yes')
     ->assertExitCode(0);

2. Testing Package Events

Event::fake([
    \YourVendor\YourPackage\Events\YourEvent::class,
]);

Event::assertDispatched(function ($event) {
    return $event instanceof YourEvent;
});

3. Testing Package Views

$view = $this->view('your-package::view.name');
$view->assertSee('Expected Text');

4. Testing Package Config

$this->app['config']->set('your-package.key', 'value');
$this->assertEquals('value', config('your-package.key'));

5. Testing Package Policies

$this->app->make('auth')->shouldUseName('YourPolicy');
$this->assertTrue($this->app['auth']->authorize('user', 'access'));

6. Testing Package Jobs/Queues

Queue::fake();
YourJob::dispatch();
Queue::assertPushed(YourJob::class);

7. Testing Package Notifications

Notification::fake();
Notification::assertSentTo(
    User::first(),
    YourNotification::class
);

Gotchas and Tips

Common Pitfalls

1. State Persistence Between Tests

  • Issue: Eloquent models, Str, or Validator states may leak between tests.
  • Fix: Testbench auto-flushes most states, but explicitly reset if needed:
    $this->app->flush();
    
  • Manual Flush:
    \Illuminate\Support\Str::flush();
    \Illuminate\Database\Eloquent\Model::flush();
    

2. Database Transactions

  • Issue: Tests may fail if transactions aren’t rolled back.
  • Fix: Use WithFixtures or manually rollback:
    $this->beginDatabaseTransaction();
    // Test code
    $this->rollBackDatabaseTransaction();
    

3. Parallel Testing Quirks

  • Issue: WithFixtures may fail in parallel mode due to shared state.
  • Fix: Ensure fixtures are idempotent or use terminate() to skip tests:
    if (!file_exists($this->getFixturesPath())) {
        Orchestra\Testbench\terminate('Fixtures not found');
    }
    

4. Environment Configuration

  • Issue: Custom .env files may not load.
  • Fix: Use testbench.yaml or override in setUp():
    $this->withEnvironmentSetup([
        'DB_CONNECTION' => 'sqlite_memory',
    ]);
    

5. Package Version Mismatches

  • Issue: Tests may fail if Laravel/Testbench versions are incompatible.
  • Fix: Use package_version_compare() to enforce constraints:
    if (!Orchestra\Testbench\package_version_compare('11.*', '^11.0')) {
        $this->markTestSkipped('Unsupported Laravel version');
    }
    

6. Mockery vs. PHPUnit Mocks

  • Issue: Conflicts between Mockery and PHPUnit’s native mocks.
  • Fix: Stick to one style or reset Mockery’s state:
    Mockery::close();
    

7. Asset Symlinks

  • Issue: Symlinks may break in CI or Windows environments.
  • Fix: Use Orchestra\Testbench\Workbench\Actions\AddAssetSymlinkFolders or disable in testbench.yaml:
    symlinks: false
    

Debugging Tips

1. Dump the Container

dd($this->app->make('config')->all());

2. Enable Debugging

$this->withEnvironmentSetup([
    'APP_DEBUG' => true,
]);

3. Log Test Output

$this->artisan('your-command', [
    '--verbose' => true,
]);

4. Inspect Providers

$this->app->register(\YourVendor\YourPackage\Providers\YourProvider::class);

5. Check for Deprecations

  • Testbench suppresses deprecations by default. To see them:
    $this->app->make('log')->error('Deprecation: ...');
    

Extension Points

1. Custom Testbench Skeleton

  • Override the default Laravel skeleton by specifying a custom path in testbench.yaml:
    skeleton: /path/to/custom/skeleton
    
  • Tip: Use orchestra/sidekick to generate skeletons dynamically.

**2. Custom

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4