Php/phpunit/サンプルコード&実行方法
提供: 初心者エンジニアの簡易メモ
目次
ファイル構成
- application/Point.php
- tests/phpunit.xml
- tests/bootstrap.php
- tests/application/PointTest.php
テスト定義xml
- tests/phpunit.xml
<phpunit bootstrap="./bootstrap.php" colors="true">
<testsuites>
<testsuite name="Application Test Suite">
<directory>./application</directory>
</testsuite>
<testsuite name="Library Test Suite">
<directory>./library</directory>
<exclude>
<directory suffix=".php">/path/to/files</directory>
<file>/path/to/file</file>
</exclude>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./</directory>
<exclude>
<directory>./library/ZendFramework-1.12.14-minimal</directory>
<directory>./vendor</directory>
</exclude>
</whitelist>
</filter>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="true"/>
</logging>
</phpunit>
テスト実行時の起動スクリプト
- tests/bootstrap.php
<?php
function autoloadphpunit($name) {
$path = __DIR__ . '/../application/' . $name . '.php';
if (file_exists($path)) {
require_once $path;
}
}
spl_autoload_register('autoloadphpunit');
ここは別に何も記述しなくてもよいが、サンプルとしてをautoloadを追加。
テスト対象クラス
- application/Point.php
<?php
class Point
{
private $_point;
public function __construct($point)
{
$this->_point = $point;
}
public function add($point)
{
if ($point < 0) $point = 0;
$this->_point += $point;
}
public function substract($point)
{
if ($point < 0) $point = 0;
if ($this->_point - $point < 0) throw new Exception('error');
$this->_point -= $point;
}
public function getPoint()
{
return $this->_point;
}
}
テストクラス
- tests/application/PointTest.php
<?php
class PointTest extends PHPUnit_Framework_TestCase
{
/**
* test処理前に必ず実行
*/
protected function setUp()
{
// print __METHOD__ . "\n";
}
/**
* @test
*/
public function testAdd()
{
$point = new Point(10);
$point->add(100);
$actual = $point->getPoint();
$expected = 110;
$this->assertThat($actual, $this->equalTo($expected), "10+100です");
}
/**
* @test
*/
public function testSubstract()
{
$point = new Point(10);
$point->substract(5);
$actual = $point->getPoint();
$expected = 5;
$this->assertThat($actual, $this->equalTo($expected), "10-5です");
}
/**
* @expectedException Exception
*/
public function testSubstract_nullstring()
{
$point = new Point(10);
$point->substract(11);
}
/**
* test処理後に必ず実行
*/
protected function tearDown()
{
// print __METHOD__ . "\n";
}
}
ExceptionはExceptionが出ないとphpunitで定義されているメッセージが表示される
phpunit実行
phpunit
実行されないテストがある場合は、ファイル名の命名規則を確認する。
phpunit実行(一つだけ実行
phpunit application/PointTest.php
phpunit実行(一つのメソッドだけ実行
phpunit application/PointTest.php --filter testHoge1
実行時の注意
--bootstrapをつけるとphpunit.xmlのbootstrapが上書きされて実行されない。
phpunit --bootstrap vendor/autoload.php tests/application/PointTest.php
phpunit.xmlの場所指定
--configuration tests/phpunit.xml
テストファイル命名規則
*Test.php
phpunit6以降
class TestCase extends \PHPUnit\Framework\TestCase {
