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 Case Laravel Package

contao/test-case

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev contao/test-case
    

    Add to your composer.json under require-dev if not using globally.

  2. Basic Test Class:

    use Contao\TestCase\ContaoTestCase;
    
    class MyFirstTest extends ContaoTestCase {}
    
  3. First Use Case: Test a Contao model interaction:

    public function testPageModel()
    {
        $page = $this->createClassWithPropertiesStub(Contao\PageModel::class, ['id' => 1, 'title' => 'Test Page']);
        $this->assertEquals('Test Page', $page->title);
    }
    

Key Entry Points

  • Symfony Container: Use getContainerWithContaoConfiguration() for dependency injection testing.
  • Framework Mocks: Start with createContaoFrameworkStub() for core Contao interactions.
  • Adapters: Use createAdapterStub() for testing Contao models (e.g., FilesModel).

Implementation Patterns

1. Testing Contao Models

Workflow:

// Stub a PageModel with predefined properties
$page = $this->createClassWithPropertiesStub(Contao\PageModel::class, [
    'id' => 42,
    'title' => 'About Us',
    'published' => true
]);

// Assert behavior
$this->assertTrue($page->published);
$this->assertEquals('About Us', $page->title);

Integration Tip: Combine with createAdapterStub() for database interactions:

$adapter = $this->createAdapterStub(['findById' => $page]);
$framework = $this->createContaoFrameworkStub([Contao\PageModel::class => $adapter]);

2. Symfony Container Testing

Pattern:

public function testContainerConfiguration()
{
    $container = $this->getContainerWithContaoConfiguration();
    $this->assertEquals(
        'files',
        $container->getParameter('contao.upload_path')
    );
}

Workflow for Custom Projects:

$container = $this->getContainerWithContaoConfiguration(__DIR__.'/../../');
$this->assertEquals(
    __DIR__.'/../../var/cache',
    $container->getParameter('kernel.cache_dir')
);

3. Token Storage for Authentication

Use Case: Test backend/front-end user logic:

public function testBackendUserToken()
{
    $tokenStorage = $this->createTokenStorageStub(Contao\BackendUser::class);
    $user = $tokenStorage->getToken()->getUser();
    $this->assertInstanceOf(Contao\BackendUser::class, $user);
}

Integration: Use with createClassWithPropertiesStub for predefined user data:

$user = $this->createClassWithPropertiesStub(Contao\BackendUser::class, [
    'username' => 'admin',
    'id' => 1
]);
$tokenStorage = $this->createTokenStorageStub($user);

4. Temporary Directories for File Testing

Pattern:

public function testFileUpload()
{
    $tempDir = $this->getTempDir();
    $fs = new \Symfony\Component\Filesystem\Filesystem();
    $fs->mkdir($tempDir.'/uploads');

    // Test file operations here...
    $this->assertFileExists($tempDir.'/uploads');
}

Critical Step: Always call parent::tearDownAfterClass() to auto-cleanup:

public static function tearDownAfterClass(): void
{
    parent::tearDownAfterClass(); // Auto-deletes temp dir
}

Gotchas and Tips

Pitfalls

  1. Temp Directory Cleanup:

    • Forgetting parent::tearDownAfterClass() causes lingering test directories.
    • Fix: Override tearDownAfterClass() in your test class.
  2. Adapter Overrides:

    • Default Config adapter in createContaoFrameworkStub() may conflict with custom configs.
    • Fix: Explicitly pass adapters:
      $framework = $this->createContaoFrameworkStub([
          Contao\Config::class => $customConfigAdapter
      ]);
      
  3. Magic Properties:

    • createClassWithPropertiesStub() fails if the class uses __get()/__set() with non-standard logic.
    • Fix: Use createAdapterStub() for complex property handling.

Debugging Tips

  1. Container Dumping:

    $container = $this->getContainerWithContaoConfiguration();
    dump($container->getParameterBag()->all()); // Inspect all params
    
  2. Framework Mock Verification:

    $framework = $this->createContaoFrameworkMock();
    $framework->expects($this->once())->method('initialize');
    // If test fails, check if `initialize()` was called.
    
  3. Adapter Stub Validation:

    • Use ->shouldReceive() for explicit method checks:
      $adapter = $this->createAdapterStub(['findById']);
      $adapter->shouldReceive('findById')->once()->andReturn($model);
      

Extension Points

  1. Custom Adapters: Extend ContaoTestCase to add project-specific adapters:

    class CustomTestCase extends ContaoTestCase
    {
        protected function createCustomAdapterStub(array $methods)
        {
            return $this->createAdapterStub($methods);
        }
    }
    
  2. Token Storage Extensions: Override createTokenStorageStub() for custom token logic:

    protected function createTokenStorageStub($user = null)
    {
        $token = $this->createMock(Contao\CoreBundle\Security\Token\ContaoUserToken::class);
        $token->method('getUser')->willReturn($user);
        $storage = $this->createMock(Contao\CoreBundle\Security\TokenStorage::class);
        $storage->method('getToken')->willReturn($token);
        return $storage;
    }
    
  3. Temp Directory Customization: Override getTempDir() for multi-project testing:

    protected function getTempDir(): string
    {
        return sys_get_temp_dir().'/myproject_'.static::class;
    }
    

Pro Tips

  • Combine with Laravel: Use getContainerWithContaoConfiguration() to test Contao integrations in Laravel:

    $container = $this->getContainerWithContaoConfiguration();
    $this->assertTrue($container->has('contao.routing.router'));
    
  • Performance: Reuse stubs/adapters across tests to avoid recreation overhead:

    private $pageStub;
    
    protected function setUp(): void
    {
        $this->pageStub = $this->createClassWithPropertiesStub(Contao\PageModel::class, ['id' => 1]);
    }
    
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