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

tipowerup/testbench

Shared Orchestra Testbench foundation for TastyIgniter v4 extensions. Boots full Laravel + TI context for tests with zero duplication: SQLite in-memory DB, array cache, core system tables/migrations, TI providers, temp paths, and extension scanning disabled for isolation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require tipowerup/testbench --dev
    

    Publish the configuration (if needed):

    php artisan vendor:publish --provider="TI\PowerUp\Testbench\TestbenchServiceProvider"
    
  2. First Test Create a basic test file in tests/Feature/ (e.g., MyExtensionTest.php):

    use TI\PowerUp\Testbench\TestCase;
    
    class MyExtensionTest extends TestCase
    {
        public function test_basic_extension()
        {
            $this->assertTrue(true); // Replace with your extension logic
        }
    }
    
  3. Key Configuration Check config/testbench.php for:

    • extensions (list of PowerUp extensions to load in tests).
    • dual_mode (host app or standalone CI).
    • database (test DB settings).

First Use Case: Testing a PowerUp Extension

// tests/Feature/ExampleExtensionTest.php
use TI\PowerUp\Testbench\TestCase;

class ExampleExtensionTest extends TestCase
{
    protected function getExtensions()
    {
        return ['TI\PowerUp\ExampleExtension'];
    }

    public function test_extension_works()
    {
        $response = $this->get('/example-route');
        $response->assertStatus(200);
    }
}

Implementation Patterns

1. Dual-Mode Testing (Host App vs. Standalone CI)

  • Host App Mode: Tests run in your Laravel app context (default).
    // config/testbench.php
    'dual_mode' => [
        'host_app' => true,
        'standalone_ci' => false,
    ],
    
  • Standalone CI Mode: Tests run in isolated CI environment (e.g., GitHub Actions).
    // Useful for CI-only tests
    $this->actingAsStandaloneCI()->get('/api/endpoint');
    

2. Extension Loading

  • Autoload Extensions: Define in getExtensions():
    protected function getExtensions()
    {
        return [
            'TI\PowerUp\AuthExtension',
            'TI\PowerUp\MediaExtension',
        ];
    }
    
  • Dynamic Loading: Load extensions conditionally:
    $this->loadExtensions(['TI\PowerUp\DebugExtension'])->testDebugTools();
    

3. Database Testing

  • Migrations & Seeders: Run migrations automatically:
    public function test_database_operations()
    {
        $this->artisan('migrate:fresh')
             ->assertExitCode(0);
    }
    
  • Factories & Models: Use Laravel’s testing tools:
    $user = User::factory()->create();
    $this->actingAs($user)->get('/profile')->assertOk();
    

4. HTTP Testing

  • API Routes: Test PowerUp API endpoints:
    public function test_api_endpoint()
    {
        $response = $this->postJson('/api/powerup', ['key' => 'value'])
                         ->assertCreated();
    }
    
  • Middleware: Test PowerUp middleware:
    $this->withHeaders(['X-PowerUp-Token' => 'test'])
         ->get('/protected-route')
         ->assertOk();
    

5. Service Container & Bindings

  • Bind Services: Override bindings in tests:
    protected function setUp(): void
    {
        $this->app->bind('TI\PowerUp\Contracts\ExampleService', function () {
            return new MockExampleService();
        });
    }
    

6. Event Testing

  • Listen for Events: Test PowerUp events:
    public function test_extension_event()
    {
        Event::fake();
        $this->artisan('powerup:event-trigger');
        Event::assertDispatched(PowerUpEvent::class);
    }
    

Gotchas and Tips

Pitfalls

  1. Extension Conflicts

    • Issue: Extensions may clash if not properly isolated.
    • Fix: Use getExtensions() to explicitly define dependencies and test them in isolation.
  2. Database State

    • Issue: Tests may fail due to leftover data from previous runs.
    • Fix: Use migrate:fresh or refresh in setUp():
      public function setUp(): void
      {
          parent::setUp();
          $this->artisan('migrate:fresh');
      }
      
  3. Dual-Mode Misconfiguration

    • Issue: Standalone CI mode may not behave like the host app.
    • Fix: Test critical paths in both modes:
      if ($this->isStandaloneCI()) {
          $this->testCIOnlyFeatures();
      } else {
          $this->testHostAppFeatures();
      }
      
  4. Service Provider Booting

    • Issue: Extensions may not load if providers aren’t registered.
    • Fix: Ensure providers are listed in config/testbench.php under extensions.
  5. Environment Variables

    • Issue: .env.testing may not be loaded.
    • Fix: Set APP_ENV=testing in phpunit.xml:
      <env name="APP_ENV" value="testing"/>
      

Debugging Tips

  1. Enable Debug Mode Add to phpunit.xml:

    <env name="APP_DEBUG" value="true"/>
    
  2. Log Output Use Laravel’s logging:

    \Log::debug('Test debug info', ['data' => $this->someData]);
    
  3. Dump Variables Use dd() or dump() in tests (but avoid in CI):

    $this->dump($this->app->make('TI\PowerUp\ExampleService'));
    
  4. Testbench Artisan Commands Run custom Artisan commands in tests:

    $this->artisan('powerup:check')
         ->expectsOutput('Extension is ready')
         ->assertExitCode(0);
    

Extension Points

  1. Custom Test Cases Extend TestCase for reusable logic:

    class PowerUpTestCase extends TestCase
    {
        protected function assertExtensionLoaded(string $extension)
        {
            $this->assertTrue(class_exists($extension));
        }
    }
    
  2. Mocking PowerUp Services Use Laravel’s mocking tools:

    $mock = Mockery::mock('TI\PowerUp\Contracts\ExampleService');
    $this->app->instance('TI\PowerUp\Contracts\ExampleService', $mock);
    
  3. Custom Assertions Add assertions for PowerUp-specific logic:

    public function assertPowerUpResponse($response, $expected)
    {
        $response->assertJsonStructure(['data', 'meta']);
        $this->assertEquals($expected, $response->json('data'));
    }
    
  4. CI-Specific Tests Use isStandaloneCI() to skip host-app-only tests in CI:

    if (!$this->isStandaloneCI()) {
        $this->testHostAppIntegration();
    }
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor