【PHPUnit】カバレッジの除外設定

PHP

PHPUnit12/11でカバレッジの対象から特定のファイルやディレクトリを除外する設定のメモです。

PHPUnit Manual — PHPUnit 12.2 Manual

前提条件

  • PHP8.2以降(PHPUnit12.xの場合はPHP8.3以降)
  • PHPUnit11.x / 12.x

フォルダ構成

例えば次のようなフォルダ構成で

「libs/Stubs/」と「libs/loader.php」をカバレッジの対象外にします。

[プロジェクト]
 ├─ libs/
 │  ├─ Core/Hoge.php
 │  ├─ Stubs/HogeStub.php ・・・カバレッジ対象外
 │  ├─ Traits/HogableTrait.php
 │  ├─ helpers.php
 │  └─ loader.php ・・・カバレッジ対象外
 ├─ tests/Unit/libs/
 │        ├─ Core/HogeTest.php
 │        ├─ Traits/HoggableTraitTest.php
 │        └─ helpersTest.php
 └─ phpunit.xml

XML設定

次のように「<sourse></srouce>」の子要素として「<exclude></exclude>」を設定すればOKです。

▼「phpunit.xml」の設定例

<phpunit
    bootstrap="libs/loader.php"
    colors="true"
    testdox="true"
    testdoxSummary="true"
    displayDetailsOnTestsThatTriggerWarnings="true"
    displayDetailsOnTestsThatTriggerErrors="true"
    displayDetailsOnTestsThatTriggerDeprecations="true"
    displayDetailsOnPhpunitDeprecations="true"
>
	<testsuites>
		<testsuite name="Libraries">
			<directory>tests/Unit/libs</directory>
		</testsuite>
	</testsuites>
	<source>
		<include>
			<directory suffix=".php">libs</directory>
		</include>
		<exclude>
			<directory>libs/Stubs</directory>
			<file>libs/loader.php</file>
		</exclude>
	</source>
	<php>
		<env name="APP_ENV" value="testing"/>
	</php>
</phpunit>

実行結果

次のコマンドでテスト実行してみます。

XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-html test_coverage

次の通り、「libs/Stubs」と「libs/loader.php」がカバレッジ結果に含まれていません。

  • 2
  • 1
  • 0
  • 0

コメント

タイトルとURLをコピーしました