下記↓の記事のコメントの通り、
PHPUnit には Functions.php
というファイルが含まれていて、これを require
するとアサーションなどがグローバル関数に登録されるので、次のようにテストを書くことができます。
<?php // 普通こう書くけど、 $this->assertThat($actual, $this->equalTo($expect)); // Functions.php を読んどけばこうも書ける。 assertThat($actual, equalTo($expect));
とても便利なんですけど Functions.php
は明示的に読む必要があります。
<?php require_once __DIR__ . '/vendor/phpunit/phpunit/src/Framework/Assert/Functions.php';
しかもこれ、PHPUnit のバージョンによって違う位置にあります。
さらに、最近なら PHPUnit を Phar で実行することもあると思います。その場合は Phar ファイル名を元に読む必要があります。
<?php require_once 'phar://phpunit-6.2.phar/phpunit/Framework/Assert/Functions.php';
こういうのが辛かったので、次のようにリフレクションでファイル名を特定するようにしていたのですが・・・PHPUnit 6 でクラス名が PEAR から PSR-4 のスタイルに変わったので、これも動かなくなりました。
<?php require __DIR__ . '/../vendor/autoload.php'; $reflection = new ReflectionClass('PHPUnit_Framework_Assert'); require_once dirname($reflection->getFileName()) . '/Assert/Functions.php';
そもそも↑のようなスニペットをいちいちコピペするのも面倒臭くなってきたので Functions.php
を自動的に読み込むやつを作りました。
次のように composer で追加しておくと、テストの実行時に自動的に Functions.php
が読まれます。
composer require --dev ngyuki/phpunit-functions
これは便利。