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

cosma/testing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require cosma/testing-bundle '2.0.*'
    

    Ensure Cosma\TestingBundle\CosmaTestingBundle is registered in config/bundles.php.

  2. Configure Fixtures Create a YAML fixture file (e.g., tests/fixtures/users.yml):

    App\Entity\User:
      user1:
        email: <email()>
        roles: ['ROLE_USER']
        plainPassword: 'password123'
    
  3. First Test Case Use the Cosma\TestingBundle\Test\WebTestCase base class:

    use Cosma\TestingBundle\Test\WebTestCase;
    
    class UserTest extends WebTestCase
    {
        public function testUserCreation()
        {
            $this->loadFixtures(['users.yml']);
            $client = static::createClient();
            $client->request('GET', '/users');
            $this->assertResponseIsSuccessful();
        }
    }
    

Key First Steps

  • Load Fixtures: Use $this->loadFixtures() in test methods.
  • Database Reset: The bundle auto-drops and recreates the schema before each test.
  • Faker Integration: Leverage <faker()> placeholders in fixtures (e.g., <name()>, <email()>).

Implementation Patterns

Workflow: Fixture-Driven Testing

  1. Define Fixtures Store fixtures in tests/fixtures/ (e.g., users.yml, posts.yml). Example with relationships:

    App\Entity\User:
      admin:
        email: admin@example.com
        roles: ['ROLE_ADMIN']
    App\Entity\Post:
      post1:
        title: '<sentence(3)>'
        author: '@admin'
    
  2. Load Fixtures Dynamically

    public function testPostCreation()
    {
        $this->loadFixtures(['users.yml', 'posts.yml']);
        // Test logic here...
    }
    
  3. Partial Fixture Loading Use loadFixtures() with specific fixture names:

    $this->loadFixtures(['users.yml:admin']); // Load only 'admin' fixture
    

Integration with Doctrine

  • Schema Management: The bundle auto-truncates tables before tests. Disable with:
    # config/packages/cosma_testing.yaml
    cosma_testing:
        reset_database: false
    

Mocking Services

Use Mockery via the bundle’s helper:

public function testMockedService()
{
    $mock = $this->getMockBuilder('App\Service\ExampleService')
        ->disableOriginalConstructor()
        ->getMock();

    $mock->method('doSomething')->willReturn('mocked!');
    $this->container->set('App\Service\ExampleService', $mock);

    // Test logic...
}

Test Cases

Extend Cosma\TestingBundle\Test\WebTestCase for web tests or Cosma\TestingBundle\Test\TestCase for non-web tests. Override getFixtures() to define default fixtures:

protected function getFixtures()
{
    return ['users.yml', 'posts.yml'];
}

Gotchas and Tips

Pitfalls

  1. Fixture Loading Order

    • Fixtures are loaded alphabetically by default. Use @ references to enforce dependencies:
      App\Entity\Post:
        post1:
          title: '<sentence(3)>'
          author: '@admin' # Requires 'admin' fixture to exist
      
  2. Database Transactions

    • The bundle does not wrap tests in transactions by default. Use @database annotation for transactional tests:
      /**
       * @database
       */
      public function testTransactional()
      {
          // Changes roll back after test.
      }
      
  3. Faker Locale

    • Faker defaults to English. Override in config/packages/cosma_testing.yaml:
      cosma_testing:
          faker_locale: 'fr_FR'
      
  4. Schema Reset Performance

    • Disabling reset_database improves speed but may cause test pollution:
      cosma_testing:
          reset_database: false
      

Debugging Tips

  1. Fixture Validation

    • Use dumpFixtures() to inspect loaded data:
      $this->loadFixtures(['users.yml']);
      $this->dumpFixtures(); // Outputs loaded entities to console.
      
  2. Mockery Debugging

    • Enable Mockery’s verbose output in phpunit.xml:
      <php>
          <env name="MOCKERY_VERBOSE" value="1"/>
      </php>
      
  3. Fixture Paths

    • Fixtures must be in tests/fixtures/ or configured via:
      cosma_testing:
          fixtures_dir: '%kernel.project_dir%/custom/fixtures'
      

Extension Points

  1. Custom Fixture Loaders Implement Cosma\TestingBundle\Loader\FixtureLoaderInterface for custom formats (e.g., JSON).

  2. Test Retries Use @retry annotation to retry flaky tests (configurable in cosma_testing.yaml):

    /**
     * @retry(3)
     */
    public function testFlaky()
    {
        // ...
    }
    
  3. Event Listeners Subscribe to cosma_testing.fixtures.load or cosma_testing.test.start events for pre/post-test logic:

    // src/EventListener/TestListener.php
    public function onTestStart(TestEvent $event)
    {
        // Setup logic...
    }
    
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