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

Data Fixtures Phpunit Laravel Package

dknx01/data-fixtures-phpunit

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Install the Bundle

    composer require --dev dknx01/data-fixtures-phpunit
    

    Ensure DoctrineFixturesBundle and PHPUnit are already installed.

  2. Create Minimal Config Add this to config/packages/data_fixtures_php_unit.yaml:

    data_fixtures_php_unit:
      faker:
    
  3. Register Fixtures as Services Define your fixture classes (e.g., App\Tests\Fixtures\UserFixture) and register them in config/services_test.yaml:

    services:
      _defaults:
        autowire: true
        autoconfigure: true
        public: false
      App\Tests\Fixtures\:
        resource: '../tests/Fixtures/*Fixture.php'
        tags: ['data_fixtures_php_unit.fixture']
    
  4. First Test Usage Use the trait in a test class:

    use Dknx01\DataFixturesPhpUnitBundle\Traits\LoadFixturesTrait;
    
    class UserTest extends TestCase
    {
        use LoadFixturesTrait;
    
        public function testUserCreation()
        {
            $this->loadFixtures(['UserFixture']);
            // Test logic here
        }
    }
    

Implementation Patterns

Common Workflows

  1. Reusable Fixtures Define fixtures in App\Tests/Fixtures/ (e.g., UserFixture, ProductFixture) and load them across tests:

    $this->loadFixtures(['UserFixture', 'ProductFixture']);
    
  2. Dynamic Fixture Loading Load fixtures conditionally based on test methods:

    public function testAdminUser()
    {
        $this->loadFixtures(['UserFixture', 'AdminRoleFixture']);
        // ...
    }
    
  3. Faker Integration Use Faker in fixtures for dynamic data:

    use Faker\Factory as Faker;
    
    class UserFixture extends Fixture
    {
        public function load(ObjectManager $manager)
        {
            $faker = Faker::create();
            $user = new User();
            $user->setEmail($faker->unique()->email);
            $manager->persist($user);
        }
    }
    
  4. Test-Specific Fixtures Override fixtures for specific test classes:

    # config/packages/test/data_fixtures_php_unit.yaml
    data_fixtures_php_unit:
      fixtures:
        default: ['App\Tests\Fixtures\BaseFixture']
    
  5. Ordering Fixtures Use order in fixture classes to enforce load sequence:

    class ProductFixture extends Fixture
    {
        public function getOrder(): int
        {
            return 1; // Loads before UserFixture (order=2)
        }
    }
    

Integration Tips

  • Database Transactions Combine with DatabaseTransactionsTrait to roll back after tests:

    use Doctrine\ORM\Tools\Setup;
    use Doctrine\DBAL\DriverManager;
    
    class UserTest extends TestCase
    {
        use LoadFixturesTrait, DatabaseTransactionsTrait;
    
        protected function setUp(): void
        {
            $this->loadFixtures(['UserFixture']);
        }
    }
    
  • Environment-Specific Fixtures Use config/packages/test/ or config/packages/dev/ to isolate fixtures.

  • Custom Fixture Providers Extend Faker with custom providers (e.g., Bundeslaender) for localized data:

    data_fixtures_php_unit:
      faker:
        locale: 'de_DE'
        providers: ['App\Tests\Faker\Bundeslaender']
    

Gotchas and Tips

Pitfalls

  1. Fixture Registration

    • Issue: Fixtures not loaded if not tagged as data_fixtures_php_unit.fixture.
    • Fix: Ensure services are registered with the correct tag in services_test.yaml.
  2. Database State Pollution

    • Issue: Fixtures persist across tests if transactions aren’t used.
    • Fix: Use DatabaseTransactionsTrait or DatabaseCleanupTrait to reset the DB.
  3. Circular Dependencies

    • Issue: Fixtures depending on each other may fail if getOrder() isn’t set.
    • Fix: Explicitly define getOrder() for all fixtures.
  4. Faker Locale Mismatch

    • Issue: Default locale (en_EN) may cause unexpected data in non-English tests.
    • Fix: Override locale in config:
      data_fixtures_php_unit:
        faker:
          locale: 'de_DE'
      
  5. Fixture Overwriting

    • Issue: Running the same fixture twice may duplicate data.
    • Fix: Use Faker::unique() or check for existing records:
      if (!$manager->getRepository(User::class)->findOneBy(['email' => $email])) {
          $manager->persist($user);
      }
      

Debugging Tips

  1. Log Fixture Execution Enable debug mode in config/packages/dev/data_fixtures_php_unit.yaml:

    data_fixtures_php_unit:
      debug: true
    
  2. Inspect Loaded Data Use Doctrine’s EntityManager to query fixtures:

    $user = $this->getEntityManager()->getRepository(User::class)->findOneBy(['email' => 'test@example.com']);
    $this->assertNotNull($user);
    
  3. Fixture Isolation For complex tests, load fixtures in setUp() and clean up in tearDown():

    public function tearDown(): void
    {
        $this->getEntityManager()->createQuery('DELETE FROM App\Entity\User')->execute();
    }
    

Extension Points

  1. Custom Fixture Loader Extend the bundle’s FixtureLoader to add pre/post-load logic:

    use Dknx01\DataFixturesPhpUnitBundle\Loader\FixtureLoader;
    
    class CustomFixtureLoader extends FixtureLoader
    {
        protected function preLoad(): void
        {
            // Custom logic (e.g., enable soft deletes)
        }
    }
    

    Register it in config:

    data_fixtures_php_unit:
      loader: 'App\Tests\Loader\CustomFixtureLoader'
    
  2. Dynamic Fixture Discovery Use autoloading for fixtures in subdirectories:

    services:
      App\Tests\Fixtures\:
        resource: '../tests/Fixtures/**/*Fixture.php'
        tags: ['data_fixtures_php_unit.fixture']
    
  3. Parallel Test Support For parallel tests, ensure fixtures are thread-safe or use test-specific databases.

  4. Fixture Validation Add assertions to fixtures to validate data integrity:

    class UserFixture extends Fixture
    {
        public function load(ObjectManager $manager)
        {
            $user = new User();
            $user->setEmail('test@example.com');
            $manager->persist($user);
            $this->assertTrue($user->getEmail() === 'test@example.com');
        }
    }
    
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.
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch