ユニットテスト|wp scaffold plugin-testsで用意される各ファイルについて調べた。
仕事でちょっとしたシステムをWordPressで作ることがあったので、ユニットテストの実行環境の用意の仕方と、調べたことをメモ。
前提
- WordPress環境
- PHPUnitがインストールされている。
自分はVCCWを使いました。
wp scaffold plugin-tests
下のコマンドを実行すると、ユニットテストに必要なファイルをダウンロードしてくる。
$ wp scaffold plugin-tests you-plugin
下記ファイルをダウンロードする。
- phpunit.xml.dist
- bin/install-wp-tests.sh
- tests/bootstrap.php
- tests/test-sample.php
- .travis.yml
各ファイルの解説
phpunit.xml.dist
PHPUnitの設定ファイル。
bootstrap=
でテストに必要な処理をする bootstrap.php
を読み込む。<testsuite></testsuite>
の中でテスト対象ファイルを指定、 <directory></directory>
で、tests/
ディレクトリにあるファイルを対象とし、prefix=
で、ファイル名がtest-
から始まり、suffix=
で、ファイル名の終わりが.php
のファイルを指定。
<?xml version="1.0"?>
<phpunit
bootstrap="tests/bootstrap.php"
backupGlobals="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
>
<testsuites>
<testsuite>
<directory prefix="test-" suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
bin/install-wp-tests.sh
指定したバージョンのWordPressをダウンロードして、上で指定したパラメーターでテスト用DBを作成します。
$ bash bin/install-wp-tests.sh wordpress_test root 'wordpress' localhost latest
実行すると /tmp
以下に、wordpress-tests-lib/
とwordpress
を作成する。(wordpress-tests-lib/
の中に、テスト用DBの設定ファイルや、TestCase を拡張させ、WordPressの関数を使えるようにした、WP_UnitTestCaseがある?)
tests/bootstrap.php
テストに必要なファイル類(テスト用DBに接続、WP_UnitTestCaseを使えるようにする、PHPUnitを使えるようにする、等?)を読み込むファイル。
tests/test-sample.php
テストのサンプルファイル。
.travis.yml
TravisCIの設定ファイル
テスト実行
tests/test-sample.phpのサンプルに沿って、テストを書き、phpunit.xml.dist
があるディレクトリでphpunit
を実行すると、テストが走る。
参考
https://phpunit.readthedocs.io/ja/latest/
https://developer.wordpress.org/cli/commands/scaffold/plugin-tests/