PHPUnitを分割実行する


はじめに

PHPUnitを分割実行して、実行後にログとカバレッジをそれぞれマージする方法です。
分割実行することでメモリ使用量を下げることができるので、大規模なプロジェクトでPHPUnitを実行するときなどに有用です。

必要なもの

phpcov

コードカバレッジのマージに必要です。

Composerでインストールします。

merge-phpunit-xml.php

ログのマージに必要です。

ダウンロードして適当な場所に配置します。

Composerでphpcovをインストールしていれば、必要なパッケージも一緒にインストールされているはずなので、下記のように書き換えてvendor/autoload.phpファイルをインクルードすれば動くはずです。

@@ -1,7 +1,6 @@
 #!/usr/bin/env php
 <?php
-require 'SebastianBergmann/FinderFacade/autoload.php';
-require 'TheSeer/fDOMDocument/autoload.php';
+require_once __DIR__ . '/vendor/autoload.php';

 use SebastianBergmann\FinderFacade\FinderFacade;
 use TheSeer\fDOM\fDOMDocument;

実行権限も与えておきます。

chmod 755 merge-phpunit-xml.php

PHPUnitの分割実行

分割前に下記のように実行していたとすると、

phpunit --log-junit /tmp/test-reports/phpunit/phpunit.result.xml --coverage-html coverage.html --coverage-xml coverage.xml

分割後は下記のように実行します。

phpunit --group group1 --log-junit /tmp/test-reports/phpunit/phpunit.result.01.xml --coverage-php /tmp/test-reports/phpunit/coverage.txt/coverage.01.txt
phpunit --group group2 --log-junit /tmp/test-reports/phpunit/phpunit.result.02.xml --coverage-php /tmp/test-reports/phpunit/coverage.txt/coverage.02.txt

この例だと、グループで分割しています。

ログのマージ

merge-phpunit-xml.php /tmp/test-reports/phpunit /tmp/test-reports/phpunit/phpunit.result.xml

第1引数にマージ前のログが置いてあるディレクトリ、第2引数にマージ後のログを出力するパスを指定します。

この例だと、/tmp/test-reports/phpunit/phpunit.result.01.xmlファイルと/tmp/test-reports/phpunit/phpunit.result.02.xmlファイルがマージされて、/tmp/test-reports/phpunit/phpunit.result.xmlファイルが生成されます。

カバレッジのマージ

phpcov merge --html /tmp/test-reports/phpunit/coverage.html --xml /tmp/test-reports/phpunit/coverage.xml /tmp/test-reports/phpunit/coverage.txt

マージしたカバレッジを色々なフォーマットで出力可能です。

この例だと、/tmp/test-reports/phpunit/coverage.txt/coverage.01.txtファイルと/tmp/test-reports/phpunit/coverage.txt/coverage.02.txtファイルがマージされて、/tmp/test-reports/phpunit/coverage.htmlディレクトリと/tmp/test-reports/phpunit/coverage.xmlディレクトリが生成されます。

参考