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

Testing Bundle Laravel Package

brightmarch/testing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require-dev brightmarch/testing-bundle --dev
    

    Add to config/bundles.php (Laravel uses config/app.php for bundles, but this is Symfony-focused; adapt via config/testing.php or service provider):

    return [
        // ...
        Brightmarch\TestingBundle\BrightmarchTestingBundle::class => ['dev' => true, 'test' => true],
    ];
    
  2. First Test Case: Extend Brightmarch\TestingBundle\TestCase in your test class:

    use Brightmarch\TestingBundle\TestCase;
    
    class UserTest extends TestCase
    {
        public function testHomepage()
        {
            $client = $this->createClient();
            $client->request('GET', '/');
            $this->assertEquals(200, $client->getResponse()->getStatusCode());
        }
    }
    
  3. First Fixture: Define a YAML fixture in tests/fixtures/users.yml:

    users:
      user1:
        email: test@example.com
        password: secret
    

    Load it in your test:

    public function setUp()
    {
        $this->loadFixtures(['users']);
    }
    

Implementation Patterns

Core Workflows

  1. Client Creation:

    • Basic Client: $client = $this->createClient();
    • Authenticated Client (for Laravel, adapt Symfony auth logic):
      $client = $this->createAuthenticatedClient('user1'); // Uses fixtures
      
    • Custom Headers/Options:
      $client = $this->createClient([
          'headers' => ['X-Custom' => 'Header'],
      ]);
      
  2. Fixtures Management:

    • Load Fixtures:
      $this->loadFixtures(['users', 'posts']); // Loads YAML files
      
    • Fixture Data Access:
      $user = $this->getFixture('users.user1'); // Access loaded fixture data
      
    • Dynamic Fixtures (Laravel adaptation): Use DatabaseSeeder-like logic in setUp() to hydrate fixtures via Eloquent.
  3. Service Container Access:

    $service = $this->getContainer()->get('service_id');
    
  4. Assertions:

    • Response:
      $this->assertEquals(200, $client->getResponse()->getStatusCode());
      $this->assertContains('Welcome', $client->getResponse()->getContent());
      
    • Database:
      $this->assertDatabaseHas('users', ['email' => 'test@example.com']);
      

Integration Tips

  • Laravel-Specific:

    • Register the bundle in AppServiceProvider:
      if ($this->app->environment('testing')) {
          $this->app->register(Brightmarch\TestingBundle\BrightmarchTestingBundle::class);
      }
      
    • Use createApplication() in phpunit.xml:
      <env name="APP_ENV" value="testing"/>
      <env name="BCRYPT_ROUNDS" value="4"/>
      
    • Override TestCase in Laravel:
      use Brightmarch\TestingBundle\TestCase as SymfonyTestCase;
      use Illuminate\Foundation\Testing\TestCase as LaravelTestCase;
      
      abstract class BaseTestCase extends LaravelTestCase
      {
          use SymfonyTestCase\Traits\ClientTrait;
          use SymfonyTestCase\Traits\FixturesTrait;
      }
      
  • Test Isolation: Use setUp()/tearDown() to reset state:

    public function tearDown()
    {
        $this->clearFixtures();
        parent::tearDown();
    }
    

Gotchas and Tips

Pitfalls

  1. Bundle Registration:

    • Symfony: Must be added to AppKernel (or config/bundles.php).
    • Laravel: Requires manual registration in a service provider or config/app.php.
    • Fix: Use a trait-based approach to avoid kernel modifications.
  2. Fixture Loading:

    • Path Assumptions: Fixtures are loaded from tests/fixtures/ by default. Customize via:
      $this->setFixturesPath(__DIR__.'/../data/fixtures');
      
    • Overwriting Data: Fixtures are loaded before each test. Use clearFixtures() to reset between tests if needed.
  3. Authenticated Clients:

    • Symfony-Specific: Relies on Symfony’s security system. For Laravel, manually authenticate:
      $client = $this->createClient();
      $client->loginUser($this->getFixture('users.user1'));
      
  4. Container Access:

    • Laravel Quirk: Symfony’s container is not directly available. Use Laravel’s container:
      $service = app('service_id');
      
  5. Database Transactions:

    • No Built-in Support: Unlike Laravel’s RefreshDatabase, this bundle does not auto-rollback transactions. Use:
      public function setUp()
      {
          DB::beginTransaction();
      }
      public function tearDown()
      {
          DB::rollBack();
      }
      

Debugging Tips

  1. Fixture Errors:

    • Validate YAML syntax. Use var_dump($this->getFixture('users.user1')) to inspect loaded data.
    • Check for missing references in YAML (e.g., circular references).
  2. Client Issues:

    • Symfony: Use $client->getProfile() to inspect requests/responses.
    • Laravel: Debug with dd($client->getResponse()->getContent()).
  3. Container Problems:

    • Ensure services are properly tagged or autowired in Symfony. For Laravel, verify service providers are loaded.

Extension Points

  1. Custom Fixture Loaders: Extend Brightmarch\TestingBundle\Loader\FixtureLoader to support JSON/XML:

    class JsonFixtureLoader extends FixtureLoader
    {
        protected function loadFile($file)
        {
            return json_decode(file_get_contents($file), true);
        }
    }
    
  2. Test Traits: Create reusable traits for common test logic:

    trait AuthenticatedClientTrait
    {
        protected function createAuthenticatedClient($fixtureName)
        {
            $client = $this->createClient();
            $user = $this->getFixture($fixtureName);
            // Laravel-specific auth logic here
            return $client;
        }
    }
    
  3. Event Listeners: Hook into fixture loading to modify data:

    $this->addFixtureListener(function ($fixtures) {
        $fixtures['users.user1']['password'] = bcrypt('secret');
        return $fixtures;
    });
    
  4. Custom Assertions: Extend Brightmarch\TestingBundle\TestCase to add domain-specific assertions:

    class CustomTestCase extends TestCase
    {
        protected function assertApiResponse($client, $expectedStatus, $expectedData)
        {
            $response = $client->getResponse();
            $this->assertEquals($expectedStatus, $response->getStatusCode());
            $this->assertJson($response->getContent());
            $this->assertEquals($expectedData, json_decode($response->getContent(), true));
        }
    }
    
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope