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

graham-campbell/testbench

Testing utilities for Laravel packages, built on PHPUnit, Mockery, Orchestral Testbench, and Laravel Testbench Core. Supports Laravel 8–13 and PHP 7.4–8.5, with compatibility for PHPUnit 9–11 to help you run fast, reliable package test suites.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev graham-campbell/testbench:^6.3
    

    No additional configuration is required—TestBench integrates seamlessly with Laravel’s testing ecosystem.

  2. First Test Case: Extend GrahamCampbell\TestBench\AbstractPackageTestCase for package tests or GrahamCampbell\TestBench\AbstractAppTestCase for application tests.

    use GrahamCampbell\TestBench\AbstractPackageTestCase;
    
    class ExampleTest extends AbstractPackageTestCase
    {
        protected function getPackageProviders($app)
        {
            return ['YourPackage\\ServiceProvider'];
        }
    
        public function test_example()
        {
            $this->assertTrue(true);
        }
    }
    
  3. Key Entry Points:

    • getPackageProviders(): Define providers to load in tests.
    • getEnvironmentSetUp($app): Customize app bootstrapping (e.g., config, migrations).
    • getBasePath(): Override for custom package paths (static in v6+).

Implementation Patterns

Core Workflows

  1. Package Testing:

    • Use AbstractPackageTestCase to test isolated package functionality.
    • Example: Mock dependencies, assert service registration, or test facade behavior.
    public function test_service_registered()
    {
        $this->assertTrue($this->app->bound('your-package-service'));
    }
    
  2. Application Testing:

    • Extend AbstractAppTestCase for full Laravel app tests (e.g., HTTP routes, jobs).
    • Leverage Laravel’s built-in testing helpers (e.g., actingAs(), assertJson()).
    public function test_route_handling()
    {
        $response = $this->get('/api/endpoint');
        $response->assertStatus(200);
    }
    
  3. Database Testing:

    • Use createApplication() with $app->loadMigrationsFrom() to set up a test database.
    protected function getEnvironmentSetUp($app)
    {
        $app->make(Kernel::class)->bootstrap();
        $app['db']->connection()->getSchemaBuilder()->create('test_table', function ($table) {
            $table->id();
        });
    }
    
  4. Mocking Services:

    • Integrate with Mockery (included) to stub services or repositories.
    $mock = Mockery::mock('alias:YourService');
    $mock->shouldReceive('method')->once();
    

Integration Tips

  • CI/CD: TestBench is optimized for CI pipelines (e.g., GitHub Actions). Use phpunit.xml to parallelize tests:
    <phpunit>
        <extensions>
            <extension class="GrahamCampbell\TestBench\PHPUnit\ParallelExtension"/>
        </extensions>
    </phpunit>
    
  • Custom Assertions: Extend AbstractTestCase to add domain-specific assertions.
  • Service Providers: Test provider booting/registration with getPackageProviders() or getApplicationProviders().

Gotchas and Tips

Pitfalls

  1. Static Methods in v6+:

    • getBasePath() and getRequiredServiceProviders() are now static. Avoid passing $app as an argument (breaks in v6+).
    // ❌ Old (v5.x)
    protected function getRequiredServiceProviders($app) { ... }
    
    // ✅ New (v6.x)
    protected static function getRequiredServiceProviders() { ... }
    
  2. PHPUnit 12 Quirks:

    • TestBench does not support PHPUnit 12 due to volatility. Stick to PHPUnit 9–11 for stability.
    • If using PHPUnit 11, ensure orchestral/testbench is pinned to ^6.0 (TestBench v6.3+ handles this).
  3. Database Transactions:

    • Tests run in transactions by default. Explicitly roll back or disable for side-effect tests:
    public function test_with_side_effects()
    {
        $this->withoutExceptionHandling();
        // Test logic...
    }
    
  4. Encryption Key:

    • TestBench sets a dummy key (base64:...). For encryption-heavy tests, override in getEnvironmentSetUp():
    $app['config']['app.key'] = 'test-key-here';
    

Debugging Tips

  • Slow Tests: Use Xdebug or --debug flag to profile bottlenecks (e.g., migrations, service resolution).
  • Mockery Warnings: Ensure mocks are verified with shouldReceive() or shouldNotReceive() to avoid silent failures.
  • Service Provider Conflicts: If providers fail to load, check getPackageProviders() for typos or missing dependencies.

Extension Points

  1. Custom Test Cases:

    • Create a base test class to share setup/teardown logic:
    abstract class BaseTestCase extends AbstractPackageTestCase
    {
        protected function setUp(): void
        {
            parent::setUp();
            // Shared setup (e.g., seed test data).
        }
    }
    
  2. Test Data Factories:

    • Use Laravel’s factories or Faker for consistent test data:
    public function test_user_creation()
    {
        $user = User::factory()->create();
        $this->assertDatabaseHas('users', ['email' => $user->email]);
    }
    
  3. Parallel Testing:

    • Enable parallel execution in phpunit.xml (requires PHPUnit 9+):
    <phpunit parallel="true" parallelConfig="phpunit.parallel.xml">
        <server name="DB_DATABASE" value="testbench_parallel"/>
    </phpunit>
    
    • Create phpunit.parallel.xml to define database connections per worker.
  4. Event Testing:

    • Listen for events in tests using expectsEvents():
    Event::fake();
    $this->app['events']->dispatch(new YourEvent());
    Event::assertDispatched(YourEvent::class);
    
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
milesj/emojibase
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