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 Core Laravel Package

orchestra/testbench-core

Orchestra Testbench Core is the foundation for testing Laravel packages. It boots a lightweight Laravel app inside your package so you can run artisan commands, migrations, routing, and more, with compatibility across Laravel 6–12.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require orchestra/testbench-core --dev
    

    Ensure version compatibility with your Laravel version (e.g., orchestra/testbench-core:^11.0 for Laravel 13).

  2. Basic Test Structure: Create a test class in tests/ (e.g., Feature/ExampleTest.php) and extend Orchestra\Testbench\TestCase:

    use Orchestra\Testbench\TestCase;
    
    class ExampleTest extends TestCase
    {
        public function test_basic()
        {
            $this->assertTrue(true);
        }
    }
    
  3. First Use Case: Load a Laravel application and test a package:

    use Orchestra\Testbench\TestCase;
    
    class PackageTest extends TestCase
    {
        protected function getPackageProviders($app)
        {
            return ['YourPackage\\ServiceProvider'];
        }
    
        public function test_package_functionality()
        {
            $this->assertTrue(true); // Replace with actual assertions
        }
    }
    

Key Entry Points

  • getPackageProviders(): Register package service providers.
  • getEnvironmentSetUp(): Configure environment (e.g., database, cache).
  • getApplication(): Customize the Laravel application instance.

Implementation Patterns

Core Workflows

1. Package Testing

  • Service Providers: Override getPackageProviders() to load your package’s providers:
    protected function getPackageProviders($app)
    {
        return [
            'YourPackage\\Providers\\AuthServiceProvider',
            'YourPackage\\Providers\\RouteServiceProvider',
        ];
    }
    
  • Configuration: Use #[WithConfig] attribute or getEnvironmentSetUp() to merge configs:
    use Orchestra\Testbench\Attributes\WithConfig;
    
    #[WithConfig('your-package')]
    class ConfigTest extends TestCase { ... }
    
    Or manually:
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('your-package.key', 'value');
    }
    

2. Database and Migrations

  • Migrations: Use Artisan::call() to run migrations:
    public function setUp(): void
    {
        parent::setUp();
        Artisan::call('migrate', ['--path' => 'tests/migrations']);
    }
    
  • Factories/Seeders: Load factories via WithFixtures trait or seeders in getEnvironmentSetUp():
    use Orchestra\Testbench\Concerns\WithFixtures;
    
    class FixtureTest extends TestCase
    {
        use WithFixtures;
    
        protected $fixtures = 'tests/fixtures/users_table.php';
    }
    

3. Artisan Commands

Execute commands directly:

$this->artisan('your:command', [
    '--option' => 'value',
])
->assertExitCode(0);

4. HTTP Testing

  • Basic Routes: Use Laravel’s get(), post(), etc., helpers:
    $response = $this->get('/api/endpoint');
    $response->assertStatus(200);
    
  • BrowserKit/Dusk: Install orchestra/testbench-browser-kit or orchestra/testbench-dusk for advanced interactions:
    $this->browser()->visit('/login')->type('email', 'test@example.com')->press('Login');
    

5. Parallel Testing

Enable parallel tests in phpunit.xml:

<phpunit ...>
    <extensions>
        <extension class="Orchestra\Testbench\Parallel\ParallelExtension" />
    </extensions>
</phpunit>

Ensure WithFixtures is compatible (use flushState() if needed).


Integration Tips

Testing Packages in Isolation

  • Use getPackageAliases() to override Laravel’s default providers:
    protected function getPackageAliases($app)
    {
        return [
            'mail' => 'YourPackage\\MailManager',
        ];
    }
    

Environment Configuration

  • Override .env via getEnvironmentSetUp():
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('database.default', 'sqlite_memory');
        putenv('DB_DATABASE=testbench');
    }
    

State Management

  • Reset global states between tests:
    public function tearDown(): void
    {
        parent::tearDown();
        \Illuminate\Support\Facades\Str::flushStates();
        \Illuminate\Validation\Validator::flushStates();
    }
    

Workbench for Local Previews

  • Install orchestra/workbench to preview your package locally:
    composer require orchestra/workbench --dev
    ./vendor/bin/workbench serve
    

Gotchas and Tips

Pitfalls

  1. Configuration Loading Timing:

    • #[WithConfig] now loads after the application boots (default defer: true). Use defer: false if you need early config:
      #[WithConfig('your-package', defer: false)]
      
  2. Parallel Testing Quirks:

    • WithFixtures may fail in parallel mode. Use flushState() or disable parallelism for fixture-heavy tests.
  3. Service Provider Binding Conflicts:

    • If your package binds to the same interface as Laravel’s core, explicitly override in getPackageAliases().
  4. Database Transactions:

    • Testbench uses transactions by default. Disable with:
      protected function getEnvironmentSetUp($app)
      {
          $app['db']->setDefaultConnection('sqlite_memory');
          $app['db']->connection()->disableSharedSchemaBuild();
      }
      
  5. Deprecated Annotations:

    • Avoid @define-env, @environment-setup, etc. Use getEnvironmentSetUp() instead.

Debugging Tips

  1. Artisan Command Failures:

    • Check exit codes and output:
      $this->artisan('migrate')
          ->expectsQuestion('confirm', 'yes')
          ->assertExitCode(0);
      
  2. Configuration Overrides:

    • Verify config is loaded with:
      $this->assertEquals('expected', config('your-package.key'));
      
  3. Service Provider Loading:

    • Debug provider registration:
      $this->assertArrayHasKey('YourPackage\\ServiceProvider', $app->getLoadedProviders());
      
  4. State Leaks:

    • Reset states explicitly:
      \Illuminate\Support\Facades\Str::flushStates();
      \Illuminate\Validation\Validator::flushStates();
      

Extension Points

  1. Custom TestCase Traits: Extend Orchestra\Testbench\TestCase to add reusable logic:

    trait WithCustomAssertions
    {
        protected function assertPackageConfig($key, $expected)
        {
            $this->assertEquals($expected, config("your-package.$key"));
        }
    }
    
  2. Dynamic Configuration: Use testbench.yaml to centralize test configurations:

    seeders: true
    providers:
        - YourPackage\\ServiceProvider
    
  3. Mocking Facades: Override facades in getEnvironmentSetUp():

    $app->instance(\Illuminate\Contracts\Auth\Factory::class, MockAuthFactory::class);
    
  4. Custom Artisan Commands: Extend Orchestra\Testbench\Foundation\Console\TerminatingConsole for custom command handling.


Performance Tips

  1. Skip Migrations in CI: Use phpunit.xml to exclude migration-heavy tests:

    <phpunit ...>
        <filter>!MigrationsTest</filter>
    </phpunit>
    
  2. Cache Configuration: Disable caching for faster iterations:

    $this->artisan('config:clear');
    
  3. Parallel Test Splitting: Group tests by concern to balance parallel workloads:

    #[Group('auth')]
    class AuthTest extends TestCase { ... }
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai