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 Laravel testing helper for package development. It boots a lightweight Laravel app for your package’s tests, making it easy to run PHPUnit/Pest suites with proper service providers, config, and environment setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev orchestra/testbench
    

    Add to your composer.json under require-dev:

    "orchestra/testbench": "^11.0"
    
  2. Basic Test Structure: Create a test class extending Orchestra\Testbench\TestCase (or Orchestra\Testbench\PHPUnit\TestCase for PHPUnit):

    use Orchestra\Testbench\TestCase;
    
    class ExampleTest extends TestCase
    {
        public function test_basic()
        {
            $this->assertTrue(true);
        }
    }
    
  3. First Use Case: Test a package service provider by overriding getPackageProviders():

    protected function getPackageProviders($app)
    {
        return ['YourPackage\\ServiceProvider'];
    }
    

Where to Look First

  • Official Documentation for API reference and advanced usage.
  • tests/TestCase.php in your package for base test configuration.
  • testbench.yaml (optional) for global test configurations like database, seeders, or environment.

Implementation Patterns

Core Workflows

1. Service Provider Testing

  • Pattern: Override getPackageProviders() to load your package’s providers.
  • Example:
    protected function getPackageProviders($app)
    {
        return [
            \YourPackage\Providers\AuthServiceProvider::class,
            \YourPackage\Providers\RouteServiceProvider::class,
        ];
    }
    
  • Tip: Use getEnvironmentSetUp() to modify the app environment before booting providers.

2. Database Testing with Fixtures

  • Pattern: Use WithFixtures trait to load test data.
  • Example:
    use Orchestra\Testbench\Concerns\WithFixtures;
    
    class UserTest extends TestCase
    {
        use WithFixtures;
    
        protected function getFixturesPath()
        {
            return __DIR__ . '/fixtures';
        }
    
        public function test_user_creation()
        {
            $user = User::factory()->create();
            $this->assertDatabaseHas('users', ['email' => $user->email]);
        }
    }
    
  • Tip: Configure testbench.yaml to auto-run seeders:
    seeders: true
    

3. Mocking and Stubbing

  • Pattern: Leverage InteractsWithMockery (included in TestCase).
  • Example:
    public function test_mocked_service()
    {
        $mock = Mockery::mock('overload:YourPackage\\Services\\UserService');
        $mock->shouldReceive('fetchUser')->andReturn(['id' => 1]);
    
        $result = app()->make('YourPackage\\Services\\UserService')->fetchUser();
        $this->assertEquals(['id' => 1], $result);
    }
    

4. HTTP Testing

  • Pattern: Use Laravel’s HTTP testing helpers with Testbench.
  • Example:
    public function test_api_route()
    {
        $response = $this->getJson('/api/endpoint');
        $response->assertStatus(200)
                 ->assertJson(['key' => 'value']);
    }
    
  • Tip: Override getPackageAliases() to alias your package’s Facades for cleaner tests.

5. Configuration Testing

  • Pattern: Publish and merge configs in tests.
  • Example:
    public function test_config_published()
    {
        $this->publishes([
            __DIR__.'/../config/your-package.php' => config_path('your-package.php'),
        ], 'config');
    
        $this->assertArrayHasKey('key', config('your-package'));
    }
    

6. Parallel Testing

  • Pattern: Use --parallel flag with PHPUnit.
  • Tip: Ensure WithFixtures is compatible (fixed in v10.11.0+).
  • Example:
    phpunit --parallel
    

Integration Tips

Custom Skeleton

  • Use Orchestra\Testbench\uses_default_skeleton() to check if the default skeleton is used.
  • Override getEnvironmentSetUp() to customize the app environment:
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('your-package.key', 'test-value');
    }
    

Remote Commands

  • Execute remote commands (e.g., Artisan) in tests:
    public function test_artisan_command()
    {
        $this->artisan('your-package:command')
             ->expectsOutput('Command output')
             ->assertExitCode(0);
    }
    

Version Comparison

  • Compare package versions programmatically:
    $this->assertTrue(\Orchestra\Testbench\package_version_compare('1.0.0', '1.0.0', '>='));
    

Flushing State

  • Reset global states between tests (e.g., Str, Validator, Model):
    public function tearDown(): void
    {
        parent::tearDown();
        \Orchestra\Testbench\flushState();
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Annotations:

    • Avoid @define-env, @environment-setup, @define-db, and @define-route (removed in v11.0.0).
    • Fix: Use getEnvironmentSetUp() or testbench.yaml instead.
  2. Parallel Testing Issues:

    • WithFixtures may fail in parallel mode (fixed in v10.11.0+).
    • Fix: Ensure you’re on v10.11.0+ or disable parallel tests temporarily.
  3. State Persistence:

    • Global states (e.g., Str::macro(), Validator rules) persist between tests unless flushed.
    • Fix: Call flushState() in tearDown() or use Orchestra\Testbench\flushState() globally.
  4. BindingResolutionException:

    • Occurs when #[UsesVendor] is used before the app is booted.
    • Fix: Ensure the app is fully booted before using attributes (fixed in v9.17.0+).
  5. SQLite Journal Files:

    • Temporary SQLite files may linger if not cleaned up.
    • Fix: Configure testbench.yaml to remove them:
      database:
          journal_mode: DELETE
      
  6. PHPUnit 13+ Compatibility:

    • Testbench v11+ supports PHPUnit 13, but older versions may break.
    • Fix: Pin to a compatible version (e.g., ^11.0 for PHPUnit 13).

Debugging Tips

  1. Environment Variables:

    • Use TESTBENCH_ENVIRONMENT_FILE to specify a custom .env file:
      TESTBENCH_ENVIRONMENT_FILE=.env.testing phpunit
      
  2. Logging:

    • Enable debug logging in testbench.yaml:
      logging:
          enabled: true
          level: debug
      
  3. Isolation Issues:

    • If tests interfere, reset the app state explicitly:
      public function tearDown(): void
      {
          $this->refreshApplication();
          parent::tearDown();
      }
      
  4. Mockery Warnings:

    • Suppress Mockery warnings with:
      Mockery::close();
      

Extension Points

  1. Custom TestCase:

    • Extend Orchestra\Testbench\PHPUnit\TestCase to add reusable methods:
      class PackageTestCase extends \Orchestra\Testbench\PHPUnit\TestCase
      {
          protected function assertPackageConfig($key, $expected)
          {
              $this->assertEquals($expected, config("your-package.$key"));
          }
      }
      
  2. Dynamic Providers:

    • Load providers conditionally:
      protected function getPackageProviders($app)
      {
          return config('your-package.enabled') ? ['YourPackage\\ServiceProvider'] : [];
      }
      
  3. Custom Assertions:

    • Add assertions to your test case:
      protected function assertRouteExists($uri)
      {
          $this->assertTrue(Route::has($uri));
      }
      
  4. Testbench YAML:

    • Centralize configurations like database, seeders, and environment:
      database:
          connection: sqlite
          migrations: true
          seeders: true
      environment:
          APP_ENV: testing
      
  5. PestPHP Support:

    • Use $__filename to resolve test file paths:
      use Orchestra\Testbench\Concerns\InteractsWithFixtures;
      
      test('example', function () {
          $this->loadFixturesFrom($__
      
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