Weave 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

Unit Bundle Laravel Package

chaplean/unit-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chaplean/unit-bundle
    

    Ensure LiipFunctionalTestBundle and DoctrineFixturesBundle are also installed (required for testing infrastructure).

  2. Register Bundles in config/bundles.php (or AppKernel.php for Symfony <5.0):

    return [
        // ...
        Chaplean\Bundle\UnitBundle\ChapleanUnitBundle::class => ['all' => true],
        Liip\FunctionalTestBundle\LiipFunctionalTestBundle::class => ['test' => true],
        Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['test' => true],
    ];
    
  3. Import Config: Add to config/packages/test/chaplean_unit.yaml (Symfony 5+) or config_test.yml (Symfony <5.0):

    imports:
        - { resource: '@ChapleanUnitBundle/Resources/config/config.yml' }
    
  4. First Use Case: Create a test class extending Chaplean\Bundle\UnitBundle\Test\WebTestCase:

    use Chaplean\Bundle\UnitBundle\Test\WebTestCase;
    
    class MyControllerTest extends WebTestCase
    {
        public function testExample()
        {
            $client = static::createClient();
            $client->request('GET', '/');
            $this->assertEquals(200, $client->getResponse()->getStatusCode());
        }
    }
    

    Run with:

    php bin/phpunit
    

Implementation Patterns

Core Workflows

  1. Service Mocking:

    • Implement MockedServiceOnSetUpInterface to define mocks globally (e.g., for external APIs, PDF generators).
    • Example:
      class MockService implements MockedServiceOnSetUpInterface
      {
          public static function getMockedServices(): array
          {
              return [
                  'guzzle.client' => \Mockery::mock(Client::class)
                      ->shouldReceive('request')
                      ->andReturn(new Response()),
              ];
          }
      }
      
    • Register in config_test.yml:
      chaplean_unit:
          mocked_service: App\Test\MockService
      
  2. Test Isolation:

    • Use setUp() to reset mocks or fixtures:
      protected function setUp(): void
      {
          parent::setUp();
          $this->resetMocks(); // Clears all mocks from previous tests
      }
      
  3. Database Fixtures:

    • Load fixtures via DoctrineFixturesBundle in tests:
      public function testWithFixtures()
      {
          $this->loadFixtures(['App\DataFixtures\ORM\LoadUserData']);
          // Test logic...
      }
      
  4. Kernel Bootstrapping:

    • Override createKernel() to customize the test environment:
      protected function createKernel(): KernelInterface
      {
          return new Kernel('test', true);
      }
      

Integration Tips

  • Dependency Injection: Use static::getContainer() to access services in tests:
    $service = static::getContainer()->get('my_service');
    
  • Assertions: Combine with PHPUnit assertions or Symfony’s Assert:
    $this->assertTrue($service->isValid());
    
  • Performance: Cache mocks or fixtures when tests are slow (e.g., using dataProvider).

Gotchas and Tips

Pitfalls

  1. Mock Lifecycle:

    • Mocks defined in MockedServiceOnSetUpInterface are reset per test method by default. Use resetMocks() explicitly if needed.
    • Avoid side effects in getMockedServices()—mock behavior should be deterministic.
  2. Configuration Overrides:

    • Test-specific config (e.g., config_test.yml) takes precedence over config/packages/ but may conflict with parameters.yml. Use environment variables for sensitive data:
      # config_test.yml
      parameters:
          app.secret: '%env(APP_SECRET)%'
      
  3. Doctrine Fixtures:

    • Fixtures are not auto-loaded. Call loadFixtures() manually or use a trait:
      use Doctrine\Bundle\FixturesBundle\Test\FixturesTrait;
      
      class MyTest extends WebTestCase
      {
          use FixturesTrait;
      }
      
  4. Symfony 5+ Compatibility:

    • Ensure config/packages/test/ is used instead of config_test.yml for Symfony 5+. The bundle may not auto-detect the new structure.

Debugging

  • Mock Verification: Use Mockery’s shouldHaveReceived() to verify interactions:
    $mock->shouldHaveReceived('method')->once();
    
  • Container Dumps: Debug service availability with:
    dump(static::getContainer()->getServiceIds());
    
  • Logs: Enable test logging in phpunit.xml:
    <php>
        <server name="KERNEL_ENV" value="test"/>
        <server name="APP_DEBUG" value="1"/>
    </php>
    

Extension Points

  1. Custom Test Cases: Extend WebTestCase to add shared setup:
    abstract class BaseTestCase extends WebTestCase
    {
        protected function setUp(): void
        {
            parent::setUp();
            $this->initCustomMocks();
        }
    }
    
  2. Dynamic Mocks: Override getMockedServices() per test class for context-specific mocks.
  3. Event Listeners: Attach listeners to kernel.test events for pre/post-test hooks:
    $dispatcher->addListener(KernelEvents::REQUEST, function (RequestEvent $event) {
        // Modify request before test
    });
    
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.
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge