はじめに
PHPUnit9系から10系にバージョンアップした際に、やったことをまとめていきます。
今回は、RectorやClineを組み合わせてすんなり上がったので、書きたくなってしまいました。
コードを修正する必要のある主な変更点
- @testはアトリビュートで#[Test]にする
以前の書き方
/**
* @test
*/
public function sample(): void {
$this->assertTrue(true);
}
10系で推奨されている書き方
#[Test]
public function sample(): void {
$this->assertTrue(true);
}
- @dataProvider もアトリビュート #[DataProvider('someProvider')]
- データプロバイダー関数はpublic かつ staticにする
以前の書き方
/**
* @test
* @dataProvider sampleDataProvider
*/
public function sampleDataProviderTest(int $a, int $b, int $expected): void {
$this->assertSame($expected, $a + $b);
}
public function sampleDataProvider(): array {
return [
[1, 1, 2],
[1, 2, 3],
[2, 2, 4],
];
}
10系で推奨されている書き方
#[Test]
#[DataProvider('sampleDataProvider')]
public function sampleDataProviderTest(int $a, int $b, int $expected): void {
$this->assertSame($expected, $a + $b);
}
public static function sampleDataProvider(): array {
return [
[1, 1, 2],
[1, 2, 3],
[2, 2, 4],
];
}
その他変更点
課題
- 今回のバージョンアップで非推奨な書き方となってしまったテストコードがたくさん出てきた
- phpunit.xmlに関しても非推奨な書き方として、警告が出るようになってしまった
やったこと
Rectorで一括変換
単純な一括変換はRectorを使うと便利である
rector.php
use Rector\Config\RectorConfig;
use Rector\PHPUnit\Set\PHPUnitSetList;
return RectorConfig::configure()
->withSets([
PHPUnitSetList::PHPUNIT_100,
]);
clineでAIにphpunit.xmlを編集してもらう
その後ドキュメントを見て変更内容が正しいか確認
https://docs.phpunit.de/en/10.5/configuration.html
phpunit.xmlに非推奨コードの箇所を出力するオプションを追加
phpunit.xml
displayDetailsOnPhpunitDeprecations="true"
1 test triggered 1 PHPUnit deprecation:
1) Tests\Unit\SampleTest::sampleDataProviderTest
Data Provider method Tests\Unit\SampleTest::sampleDataProvider() is not static
まとめ
以上の方法で、修正箇所が大量にあるPHPUnitのバージョンアップを比較的対応時間少なく対応できた。
すでにPHPUnit11もリリースされており、近い未来にバージョンアップ対応予定であるので忘れないためにまとめておきます。