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

Test Framework Bundle Laravel Package

aureja/test-framework-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require aureja/test-framework-bundle "dev-master"
    

    Ensure your composer.json meets the package's PHP/Symfony version requirements (PHP ≥5.5, Symfony 2.7/3.0).

  2. Register the Bundle: Add to AppKernel.php (Symfony 2.x) or config/bundles.php (Symfony 3.x+):

    new Aureja\Bundle\TestFrameworkBundle\AurejaTestFrameworkBundle(),
    
  3. First Test Case: Extend Aureja\Bundle\TestFrameworkBundle\Test\WebTestCase and annotate with @dbIsolation or @dbIsolationPerTest:

    use Aureja\Bundle\TestFrameworkBundle\Test\WebTestCase;
    
    /**
     * @dbIsolationPerTest
     */
    class UserTest extends WebTestCase
    {
        protected function setUp()
        {
            $this->initClient(); // Required for Symfony's WebTestCase
        }
    
        public function testUserCreation()
        {
            // Test logic here
        }
    }
    
  4. Run Tests:

    phpunit
    

Key First Use Case

Database Isolation for Functional Tests:

  • Use @dbIsolation to share a database schema across all tests in a class (faster, but tests may interfere).
  • Use @dbIsolationPerTest to reset the database schema before each test (slower, but isolated state).
  • Ideal for testing CRUD operations, API endpoints, or workflows where data integrity is critical.

Implementation Patterns

1. Database Setup/Teardown

Workflow:

  • Override setUp() to initialize the client (Symfony's initClient()) and load fixtures if needed.
  • Use annotations to control database isolation:
    /**
     * @dbIsolation
     */
    class SharedDbTest extends WebTestCase { ... }
    
    /**
     * @dbIsolationPerTest
     */
    class IsolatedDbTest extends WebTestCase { ... }
    

Example with Fixtures:

protected function setUp()
{
    $this->initClient();
    $this->loadFixtures([
        'AppBundle/DataFixtures/ORM/LoadUserData.php',
    ]);
}

2. Integration with Symfony Components

Client Initialization: Always call $this->initClient() in setUp() to ensure Symfony's test client is ready for HTTP requests.

Doctrine Integration: Leverage Doctrine's EntityManager for database operations:

public function testEntityPersistence()
{
    $em = $this->getContainer()->get('doctrine')->getManager();
    $user = new User();
    $em->persist($user);
    $em->flush();

    // Assertions...
}

3. Custom Test Classes

Extend WebTestCase for reusable test logic:

abstract class BaseTest extends WebTestCase
{
    protected function setUp()
    {
        $this->initClient();
        $this->enableProfiler(); // Optional: For debugging
    }

    protected function enableProfiler()
    {
        if (!$this->client->getProfile()) {
            $this->client->enableProfiler();
        }
    }
}

Usage:

class ApiTest extends BaseTest { ... }

4. Configuration

Environment-Specific Config: Override database settings in phpunit.xml or .env.testing:

<!-- phpunit.xml -->
<env name="DATABASE_URL" value="sqlite:///:memory:" />

Bundle Configuration: The bundle does not expose public configuration options, but you can override Doctrine's test configuration via config/packages/test/doctrine.yaml:

doctrine:
    dbal:
        url: '%env(DATABASE_URL)%'
        # Other DBAL config...

Gotchas and Tips

Pitfalls

  1. Missing initClient():

    • Forgetting to call $this->initClient() in setUp() will cause HTTP-related tests to fail with Client not initialized errors.
  2. Database Isolation Overhead:

    • @dbIsolationPerTest resets the database before each test, which can slow down test suites. Use @dbIsolation for faster tests when isolation isn’t critical.
  3. Symfony 3.x+ Compatibility:

    • The bundle targets Symfony 2.7/3.0 but may not work out-of-the-box with newer Symfony versions (e.g., 4.x+). Check for deprecations in AppKernel.php (e.g., registerBundles() vs. bundles.php).
  4. Doctrine Migrations:

    • If using migrations, ensure they are run before tests or handle them in setUp():
      $this->runMigrations();
      
      (Note: The bundle does not provide this functionality; implement custom logic if needed.)

Debugging Tips

  1. Database State:

    • Use Doctrine's SchemaTool to inspect the database schema:
      $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->getEntityManager());
      $schema = $schemaTool->getSchema();
      
  2. Profiler:

    • Enable Symfony's profiler in setUp() to debug HTTP requests:
      $this->client->enableProfiler();
      $this->client->request('GET', '/');
      $this->client->getProfile()->getCollector('db')->getData();
      
  3. Logs:

    • Enable Doctrine logging in phpunit.xml:
      <php>
          <env name="DOCTRINE_LOGGING" value="1" />
      </php>
      

Extension Points

  1. Custom Database Isolation:

    • Override the bundle's isolation logic by extending WebTestCase and implementing your own setUp()/tearDown():
      class CustomTest extends WebTestCase
      {
          protected function setUp()
          {
              $this->initClient();
              $this->customDbSetup();
          }
      
          private function customDbSetup()
          {
              // Custom logic (e.g., seed data, truncate tables)
          }
      }
      
  2. Event Listeners:

    • Attach listeners to Doctrine events for pre/post-test database operations:
      $em->getEventManager()->addEventListener(
          \Doctrine\ORM\Events::onFlush,
          function () { /* Pre-flush logic */ }
      );
      
  3. Fixtures:

    • Combine with Hautelook/AliceBundle for complex fixtures:
      $this->loadFixtures([
          new LoadUserData(),
          new LoadProductData(),
      ]);
      

Performance Optimization

  • Batch Fixtures: Load fixtures once per test class (not per test) when using @dbIsolation.
  • Skip Isolation: Use @dbIsolation for unit tests that don’t require a full database reset.
  • Parallel Tests: If using PHPUnit parallelization, ensure database connections are isolated per worker.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle