1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPUnit9系から10系のバージョンアップをClineとRectorを使用して行う

Posted at

はじめに

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 Deprecations: 1という形で個数を教えてくれるようになった
    image.png

課題

  • 今回のバージョンアップで非推奨な書き方となってしまったテストコードがたくさん出てきた
  • 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を編集してもらう

設定ファイル系は、AIに書かせると精度が高い結果を得られる
image.png

その後ドキュメントを見て変更内容が正しいか確認
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もリリースされており、近い未来にバージョンアップ対応予定であるので忘れないためにまとめておきます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?