composer require --dev symfony/test-pack
+    "require-dev": {
+        "phpunit/phpunit": "^9.5",
+        "symfony/browser-kit": "7.2.*",
+        "symfony/css-selector": "7.2.*",
+        "symfony/phpunit-bridge": "^7.2"
[!NOTE] composer.json の下記記述は symfony/test-pack 導入時ではなくて symfony new 実行時に設定されます。
"autoload-dev": { "psr-4": { "App\Tests\": "tests/" } },
[!IMPORTANT] 親クラスはおもに以下のクラスを使用します。
- 単体テスト PHPUnit 提供クラス
PHPUnit\Framework\TestCaseclass SampleTest extends \PHPUnit\Framework\TestCase { }- 結合テスト Symfony 提供クラス
Symfony\Bundle\FrameworkBundle\Test\KernelTestCaseclass SampleTest extends \Symfony\Bundle\FrameworkBundle\Test\KernelTestCase { }
<?php
namespace App\Service;
class Sample
{
    public function echo(string $message): string
    {
        return $message;
    }
}
<?php
namespace App\Tests\Service;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use App\Service\Sample;
// KernelTestCase を継承
class SampleServiceTest extends KernelTestCase
{
    public function testSomething(): void
    {
        // (1) boot the Symfony kernel
        self::bootKernel();
        // (2) use static::getContainer() to access the service container
        $container = static::getContainer();
        // (3) run some service & test the result
        $sample = $container->get(Sample::class);
        $this->assertEquals('Hello World!', $sample->echo('Hello World!'));
    }
}
上記は テスト対象のサービスが public でないとエラーになります。
services_test.yaml を使ってテストのときだけ public にできます。
# config/services.yaml
// ...
    # service
    App\Service\Sample:
        public: false
// ...
# config/services_test.yaml
services:
    App\Service\Sample:
        public: true # テストのときだけ public にする
[!IMPORTANT] services_test.yaml はテストのときだけ読み込まれて以下のように動作します。
- services.yaml に定義されたサービスはすべて適用される
- services_test.yaml に同じサービスがある場合は、それが上書きされる
- services_test.yaml に新しいサービスを追加できる