Memo

メモ > 技術 > 開発: PHPUnit > 導入

■導入
自分の環境に合わせて 「Windows+コマンドプロンプト+PHPUnit」 でPHPプログラムのテストをしてみたので、手順をメモ。 参考 https://phpunit.de/manual/current/ja/installation.html https://phpunit.de/ から phpunit.phar の安定版を入手する。 PHP5で使う場合、PHPUnitは5をダウンロードする。 任意のディレクトリ内(C:\xxx\phpunit とする)に phpunit.phar を配置する。 C:\xxx\phpunit 内に phpunit.cmd を作成し、以下の内容を記述する。 (PHPへのパスは環境に合わせて設定する。) @C:\xampp\php\php.exe "%~dp0phpunit.phar" %* コマンドプロンプトで C:\xxx\phpunit 内に移動し、以下のコマンドを実行。 バージョン情報が表示されれば成功。
C:\xxx\phpunit>phpunit --version PHPUnit 5.7.14 by Sebastian Bergmann and contributors.
■サンプルで動作確認 参考 https://phpunit.de/getting-started.html
C:\xxx\phpunit\src\Money.php (テストしたいクラス)を作成 C:\xxx\phpunit\tests\MoneyTest.php (テスト用プログラム)を作成 C:\xxx\phpunit>phpunit --bootstrap src/Money.php tests/MoneyTest PHPUnit 4.5.0 by Sebastian Bergmann and contributors. . Time: 31 ms, Memory: 4.00Mb OK (1 test, 1 assertion)
phpunitコマンドでテストし、上のように表示されればテスト成功。 ■自作のプログラムで動作確認 参考 https://phpunit.de/manual/current/ja/writing-tests-for-phpunit.html C:\xxx\phpunit\src\calculate.php を作成し、掛け算と割り算の計算結果を返す命令を定義。 これらの命令が正しく動作しているかテストする。
<?php function multiplication($x, $y) { return $x * $y; } function division($x, $y) { return $x / $y; }
C:\xxx\phpunit\tests\calculate.php を作成し、各命令をテストするコードを書く。 (計算結果が正しく返ってくればテスト成功とする。)
<?php require_once 'C:/localhost/home/test/public_html/phpunit/src/calculate.php'; class Calculate extends PHPUnit_Framework_TestCase { public function testCalculate() { $this->assertEquals(8, multiplication(4, 2)); $this->assertEquals(2, division(4, 2)); } }
以下のとおり実行
C:\xxx\phpunit>phpunit tests/calculate PHPUnit 4.5.0 by Sebastian Bergmann and contributors. . Time: 30 ms, Memory: 4.00Mb OK (1 test, 2 assertions)
上のように表示されればテスト成功。 試しに関数の内容を間違ったものにしてテストすると。
FAILURES! Tests: 1, Assertions: 2, Failures: 1.
のような結果が表示されるので、正しくテストできていることが確認できる。

Advertisement