Installation
composer require --dev symfony/test-pack
Add the TestPack to your composer.json under extra:
"extra": {
"symfony": {
"pack": ["symfony/test-pack"]
}
}
First Use Case: Functional Test
Create a basic test class in tests/Functional/:
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ExampleTest extends WebTestCase
{
public function testHomepage(): void
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertResponseIsSuccessful();
}
}
Key Files to Explore
config/packages/test.php (Symfony’s built-in test config)tests/Functional/ (Default test directory structure)var/cache/test/ (Test cache location)Database Testing
Use DatabaseTestCase for isolated DB tests:
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class UserTest extends KernelTestCase
{
protected function setUp(): void
{
self::bootKernel();
$this->loadFixtures([UserFixtures::class]);
}
}
Client-Based Testing
Leverage WebTestCase for HTTP interactions:
$client = static::createClient();
$client->loginUser($user); // Auth helper
$client->request('POST', '/api/users', ['name' => 'John']);
$this->assertJson($client->getResponse()->getContent());
Integration with PHPUnit
Annotate tests with @group integration for CI filtering:
/**
* @group integration
*/
class PaymentTest extends WebTestCase { ... }
DoctrineFixturesBundle for reusable test data.php bin/console cache:clear --env=test.--parallel flag for faster execution.Environment Mismatch
Ensure APP_ENV=test and APP_DEBUG=1 in .env.test.
Fix: Run php bin/console config:dump --env=test to debug.
Static Analysis Conflicts
TestPack may trigger static analyzers (e.g., Psalm) due to static:: calls.
Fix: Add @mixin annotations or exclude test files.
Slow Tests
Avoid self::bootKernel() in every test; reuse the kernel where possible.
$this->assertResponseStatusCodeSame(200);
$this->assertSelectorTextContains('h1', 'Welcome');
config/packages/dev/test.php:
monolog:
handlers:
test:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
Custom Test Cases
Extend WebTestCase for shared setup:
abstract class ApiTestCase extends WebTestCase
{
protected function createAuthenticatedClient(): Client
{
$client = static::createClient();
$client->loginUser($this->createTestUser());
return $client;
}
}
Test Utilities
Create a tests/_utils/ directory for helper classes (e.g., TestClientFactory).
Custom Assertions
Use PHPUnit’s assertThat() with custom matchers:
$this->assertThat(
$client->getResponse()->getContent(),
$this->stringContains('Expected text')
);
How can I help you explore Laravel packages today?