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

culabs/testing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the bundle to your composer.json:

    composer require culabs/testing-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Culabs\TestingBundle\CulabsTestingBundle::class => ['all' => true],
    ];
    
  2. First Use Case The bundle provides a base TestCase class for Symfony applications. Extend it in your test class:

    use Culabs\TestingBundle\Test\WebTestCase;
    
    class MyTest extends WebTestCase
    {
        public function testExample()
        {
            $client = static::createClient();
            $client->request('GET', '/');
            $this->assertEquals(200, $client->getResponse()->getStatusCode());
        }
    }
    
  3. Where to Look First

    • Documentation: Check the GitHub README for basic usage.
    • TestCase Class: Explore Culabs\TestingBundle\Test\WebTestCase for built-in methods and overrides.
    • Configuration: Review config/packages/culabs_testing.yaml (if provided) for customizable settings.

Implementation Patterns

Usage Patterns

  1. Base TestCase Extension Extend WebTestCase for all functional tests to inherit common setup/teardown logic:

    class ApiTest extends WebTestCase
    {
        protected function setUp(): void
        {
            parent::setUp();
            // Custom setup (e.g., load fixtures)
        }
    }
    
  2. Client Management Reuse the createClient() method for API/HTTP tests:

    public function testLogin()
    {
        $client = static::createClient();
        $client->request('POST', '/api/login', [
            'json' => ['email' => 'test@example.com', 'password' => 'password']
        ]);
        $this->assertJson($client->getResponse()->getContent());
    }
    
  3. Assertion Helpers Use built-in assertions (if any) or integrate with PHPUnit/Symfony’s assertions:

    $this->assertResponseIsSuccessful();
    $this->assertJsonContains(['status' => 'success']);
    
  4. Database Transactions Leverage Symfony’s test database isolation (enabled by default in WebTestCase):

    // No need for manual rollback; transactions auto-commit after tests.
    
  5. Service Container Access Access services in tests via static::$container:

    $mailer = static::$container->get('mailer');
    

Workflows

  1. Feature Testing Workflow

    • Extend WebTestCase.
    • Use createClient() for HTTP interactions.
    • Assert responses with PHPUnit or custom helpers.
  2. Integration with Fixtures Load fixtures in setUp():

    protected function setUp(): void
    {
        parent::setUp();
        $this->loadFixtures([UserFixtures::class]);
    }
    
  3. Mocking Services Override services in tests:

    protected function getKernelClass()
    {
        return Kernel::class;
    }
    
    protected function createKernel()
    {
        $kernel = parent::createKernel();
        $kernel->getContainer()->set('my_service', $this->createMock(MyService::class));
        return $kernel;
    }
    

Integration Tips

  1. Combine with Other Bundles

  2. Custom Assertions Add reusable assertions to a trait:

    trait Assertions
    {
        protected function assertJsonPath($path, $expected)
        {
            $json = json_decode($this->getJsonResponseContent(), true);
            $this->assertArrayHasKey($path, $json, "JSON path '$path' not found");
            $this->assertEquals($expected, $json[$path]);
        }
    }
    
  3. Parallel Testing Configure PHPUnit for parallel execution in phpunit.xml.dist:

    <phpunit>
        <extensions>
            <extension class="Parallel\Tests\ParallelExtension" />
        </extensions>
    </phpunit>
    

Gotchas and Tips

Pitfalls

  1. Lack of Documentation

    • The bundle has minimal documentation. Assume undocumented features may not exist or behave unpredictably.
    • Workaround: Inspect the source code (src/Test/WebTestCase.php) for behavior.
  2. Symfony 2 vs. 5+ Compatibility

    • The bundle is labeled for Symfony 2 but may not fully support newer Symfony versions (e.g., 5/6).
    • Workaround: Check for deprecation warnings or fork the bundle if critical features are missing.
  3. No Built-in Assertions

  4. Database Isolation

    • While transactions are enabled, complex tests with side effects (e.g., file uploads) may still require cleanup.
    • Workaround: Use setUp()/tearDown() to reset state.
  5. Service Container Access

    • Directly accessing static::$container bypasses dependency injection and may cause issues in some contexts.
    • Workaround: Use Symfony’s self::$kernel->getContainer() or inject dependencies via constructor.

Debugging

  1. Kernel Boot Issues

    • If tests fail with KernelException, ensure the bundle is enabled in bundles.php and dependencies are installed.
    • Debug: Run php bin/console debug:container to check for missing services.
  2. Client Configuration

    • Misconfigured clients (e.g., wrong environment) may lead to silent failures.
    • Debug: Dump the client’s environment:
      $client = static::createClient(['environment' => 'test']);
      $this->assertEquals('test', $client->getKernel()->getEnvironment());
      
  3. Fixture Loading

    • Fixtures may not load due to missing dependencies or incorrect syntax.
    • Debug: Enable Doctrine debug mode in config/packages/dev/doctrine.yaml:
      doctrine:
          dbal:
              logging: true
              profiling: true
      

Config Quirks

  1. No Configuration File

    • The bundle does not provide a culabs_testing.yaml config file by default.
    • Workaround: Create one in config/packages/culabs_testing.yaml if needed:
      culabs_testing:
          default_locale: en
          # Custom settings (if supported)
      
  2. Environment-Specific Settings

    • Test behavior may vary across environments (e.g., test vs. dev).
    • Tip: Use createClient(['environment' => 'test']) explicitly to avoid surprises.

Extension Points

  1. Custom TestCase Override WebTestCase to add shared logic:

    class CustomTestCase extends WebTestCase
    {
        protected function createClient(array $options = [], array $server = [])
        {
            $options['debug'] = true; // Enable debug toolbar for all tests
            return parent::createClient($options, $server);
        }
    }
    
  2. Event Listeners Attach listeners to test events (if the bundle supports them):

    // Example: Listen to kernel.events (hypothetical)
    $dispatcher = static::$kernel->getContainer()->get('event_dispatcher');
    $dispatcher->addListener(KernelEvents::REQUEST, function () {
        // Pre-request logic
    });
    
  3. Fixtures Integration Extend fixture loading in setUp():

    protected function loadFixtures(array $fixtures)
    {
        $loader = static::$kernel->getContainer()->get('doctrine.fixtures.loader');
        foreach ($fixtures as $fixture) {
            $loader->load($fixture);
        }
    }
    
  4. API Testing Helpers Create a trait for common API test patterns:

    trait ApiTestTrait
    {
        protected function assertApiSuccess($response)
        {
            $this->assertEquals(200, $response->getStatusCode());
            $this->assertJson($response->getContent());
        }
    
        protected function assertApiError($response, $status = 400)
        {
            $this->assertEquals($status, $response->getStatusCode());
            $this->assertJson($response
    
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.
terminal42/code-quality-tools
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