第6章 例外やパフォーマンス低下をテストする

テストクラスの基底クラスである PHPUnit2_Framework_TestCase を拡張するための方法を、PHPUnit では二通り提供しています。これにより、 例外やパフォーマンス低下のテストができるようになります。

例外

例外をテストするにはどうすればいいのでしょう? 例外が発生したかどうかを直接検出することはできないので、その代わりに PHP の例外処理機能を使用してテストを書きましょう。 例外をテストするための例を以下に示します。

<?php
require_once 'PHPUnit2/Framework/TestCase.php';
 
class ExceptionTest extends PHPUnit2_Framework_TestCase {
    public function testException() {
        try {
            // ... 例外が発生するはずのコード ...
        }
 
        catch (Exception $expected) {
            return;
        }
 
        $this->fail('期待通りの例外が発生しませんでした。');
    }
}
?>

例外が発生するはずのコードで例外が発生しなかった場合、その後の fail() (表14.2「ボトルネックメソッド」 を参照ください) のコールでテストが中断され、テストで問題が発生したことを通知します。 期待通りに例外が発生した場合は catch ブロックが実行され、テストは正常に終了します。

別の方法としては、PHPUnit2_Extensions_ExceptionTestCase を継承したテストクラスを作成し、 テストコードの内部で例外がスローされたかどうかを調べることもできます。 例6.1「PHPUnit2_Extensions_ExceptionTestCase の使用法」 では、PHPUnit2_Extensions_ExceptionTestCase のサブクラスを作成し、テストしたい例外をその setExpectedException() メソッドに設定する方法を示します。期待した例外がスローされなかった場合は、 そのテストは失敗という扱いになります。

例6.1 PHPUnit2_Extensions_ExceptionTestCase の使用法

<?php
require_once 'PHPUnit2/Extensions/ExceptionTestCase.php';
 
class ExceptionTest extends PHPUnit2_Extensions_ExceptionTestCase {
    public function testException() {
        $this->setExpectedException('Exception');
    }
}
?>
phpunit ExceptionTest
PHPUnit 2.3.0 by Sebastian Bergmann.

F

Time: 0.006798
There was 1 failure:
1) testException(ExceptionTest)
Expected exception Exception

FAILURES!!!
Tests run: 1, Failures: 1, Errors: 0, Incomplete Tests: 0.


表6.1「ExceptionTestCase の外部プロトコル」 は、PHPUnit2_Extensions_ExceptionTestCase が実装している外部プロトコルをまとめたものです。

表6.1 ExceptionTestCase の外部プロトコル

メソッド意味
void setExpectedException(string $exceptionName)発生することを期待する例外の名前を $exceptionName に設定します。
String getExpectedException()発生することを期待する例外の名前を返します。


パフォーマンス低下

PHPUnit2_Extensions_PerformanceTestCase を継承したテストクラスを使用すると、 関数やメソッドの実行が制限時間内に終わったかどうかなどをテストすることができます。

PHPUnit2_Extensions_PerformanceTestCase のサブクラスを作成してその setMaxRunningTime() メソッドを使用し、実行時間の最大値を制限する方法を 例6.2「PHPUnit2_Extensions_PerformanceTestCase の使用法」 で示します。 もしテストが制限時間内に終了しなければ、そのテストは失敗という扱いになります。

例6.2 PHPUnit2_Extensions_PerformanceTestCase の使用法

<?php
require_once 'PHPUnit2/Extensions/PerformanceTestCase.php';
 
class PerformanceTest extends PHPUnit2_Extensions_PerformanceTestCase {
    public function testPerformance() {
        $this->setMaxRunningTime(2);
        sleep(1);
    }
}
?>


表6.2「PerformanceTestCase の外部プロトコル」 は、PHPUnit2_Extensions_PerformanceTestCase. が実装している外部プロトコルをまとめたものです。

表6.2 PerformanceTestCase の外部プロトコル

メソッド意味
void setMaxRunningTime(int $maxRunningTime)テストの所要時間の最大値を (秒単位で) $maxRunningTime に設定します。
integer getMaxRunningTime()このテストの最大所要時間を返します。