以下、自分用の作業メモです。
Symfony 5でユニットテストを作成(PHPUnitとTestingコンポーネント使用)
Symfony 5でユニットテストを作成するには、PHPUnitとSymfonyのTestingコンポーネントを組み合わせて使用します。以下は、基本的な手順と例です。
- PHPUnitのインストール:
最初に、PHPUnitをインストールします。composer.json
ファイルに以下のように追加して、依存関係をインストールします。
{
"require-dev": {
"phpunit/phpunit": "^9.0"
}
}
インストールが終わったら、コマンドラインで phpunit
コマンドが実行可能か確認してください。
- Symfony Testingコンポーネントのセットアップ:
SymfonyのTestingコンポーネントはSymfonyアプリケーションのテストをサポートします。phpunit.xml.dist
ファイルをプロジェクトルートに作成し、次のように設定します。
<!-- phpunit.xml.dist -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.0/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php">
<php>
<server name="APP_ENV" value="test"/>
<server name="SHELL_VERBOSITY" value="-1"/>
<server name="SYMFONY_DEPRECATIONS_HELPER" value="weak"/>
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>src</directory>
<exclude>
<file>src/Kernel.php</file>
<file>src/DataFixtures</file>
<file>src/Command</file>
</exclude>
</whitelist>
</filter>
</phpunit>
上記の例では、tests
ディレクトリ内のテストが実行されるように設定されています。
- テストの作成:
例として、Symfonyアプリケーションのsrc/Service/MathService.php
というサービスクラスのメソッドをテストするPHPUnitのテストクラスを作成します。
// tests/Service/MathServiceTest.php
namespace App\Tests\Service;
use App\Service\MathService;
use PHPUnit\Framework\TestCase;
class MathServiceTest extends TestCase
{
public function testAdd()
{
$mathService = new MathService();
$result = $mathService->add(2, 3);
$this->assertEquals(5, $result);
}
}
この例では MathService
クラスの add
メソッドをテストしています。
- テストの実行:
テストを実行するには、コマンドラインで以下のコマンドを実行します。
php bin/phpunit
テストが実行され、結果が表示されるはずです。テストが正常に通過すると、テストが成功したことを示すメッセージが表示されます。
これで、Symfony 5での基本的なユニットテストの作成と実行が完了しました。各テストクラスは対応するクラスやメソッドの動作を確認するためのもので、これをベースにアプリケーションの各部分をテストするためのテストクラスを追加していくことができます。