| Prev | Next |
たいていの場合は、PHPUnit の API は単純なものです。単に PHPUnit_Framework_TestCase を継承したテストケースを作成し、 assertTrue() あるいは assertEquals() をコールすればよいのです。しかし、PHPUnit をより深く知りたい方のために、 ここではすべてのクラスおよび公開メソッドを説明します。
ほとんどの場合、PHPUnit を使用する際には以下の 5 つのクラスやインターフェイスに出会うことになるでしょう。
PHPUnit_Framework_Assert
実際の値が想定した値どおりかどうかを調べるための静的メソッドを集めたもの。
PHPUnit_Framework_Test
テストケースとして動作するすべてのオブジェクトのインターフェイス。
PHPUnit_Framework_TestCase
ひとつのテスト。
PHPUnit_Framework_TestSuite
テストの集まり。
PHPUnit_Framework_TestResult
ひとつあるいは複数のテストの実行結果をまとめたもの。
PHPUnit の、5 つの基本クラス/インターフェイスである PHPUnit_Framework_Assert、 PHPUnit_Framework_Test、 PHPUnit_Framework_TestCase、 PHPUnit_Framework_TestSuite およびand PHPUnit_Framework_TestResult の関係を 図 22.1 に示します。
PHPUnit 用に書かれたテストケースのほとんどは、間接的に PHPUnit_Framework_Assert を継承しています。ここには、 値を自動的にチェックして矛盾を報告するためのメソッドが含まれています。 これらのメソッドは静的に宣言されているので、 あなたが作成したメソッドの中で「規約による設計」方式のアサーションを使用し、 PHPUnit に結果を報告させることができます (例 22.1 を参照ください)。
例 22.1: 「規約による設計」方式のアサーション
<?php
require_once 'PHPUnit/Framework.php';
class Sample
{
public function aSampleMethod($object)
{
PHPUnit_Framework_Assert::assertNotNull($object);
}
}
$sample = new Sample;
$sample->aSampleMethod(NULL);
?>
Fatal error: Uncaught exception 'PHPUnit_Framework_ExpectationFailedException' with message 'Failed asserting that <null> is not identical to <null>'.
しかし、ほとんどの場合はこれらのアサーションはテストの中で行います。
各アサーションメソッドには 2 種類の方式があります。 エラー時に表示されるメッセージをパラメータとして指定する方法としない方法です。 オプションで指定したメッセージは、通常はテストが失敗したことが報告される場面で 表示されます。これにより、デバッグが楽になります。
例 22.2: メッセージつきのアサーション
<?php
require_once 'PHPUnit/Framework.php';
class MessageTest extends PHPUnit_Framework_TestCase
{
public function testMessage()
{
$this->assertTrue(FALSE, 'これは独自のメッセージです。');
}
}
?>
以下の例は、 例 22.2 のテスト testMessage() でメッセージつきのアサーションを使用した場合の出力結果です。
phpunit MessageTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testMessage(MessageTest)
これは独自のメッセージです。
Failed asserting that <boolean:false> is true.
/home/sb/MessageTest.php:8
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
以下に、すべてのアサーションをまとめます。
assertArrayHasKey(mixed $key, array $array[, string $message = ''])
$array にキー $key が存在しない場合にエラー $message を報告します。
assertArrayNotHasKey() はこのアサーションの逆で、同じ引数をとります。
例 22.3: assertArrayHasKey() の使用法
<?php
class ArrayHasKeyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertArrayHasKey('foo', array('bar' => 'baz'));
}
}
?>
phpunit ArrayHasKeyTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) ArrayHasKeyTest::testFailure
Failed asserting that an array has the key <string:foo>.
/home/sb/ArrayHasKeyTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertClassHasAttribute(string $attributeName, string $className[, string $message = ''])
$className::attributeName が存在しない場合にエラー $message を報告します。
assertClassNotHasAttribute() はこのアサーションの逆で、同じ引数をとります。
例 22.4: assertClassHasAttribute() の使用法
<?php
class ClassHasAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertClassHasAttribute('foo', 'stdClass');
}
}
?>
phpunit ClassHasAttributeTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) ClassHasAttributeTest::testFailure
Failed asserting that class "stdClass" has attribute "foo".
/home/sb/ClassHasAttributeTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertClassHasStaticAttribute(string $attributeName, string $className[, string $message = ''])
$className::attributeName が存在しない場合にエラー $message を報告します。
assertClassNotHasStaticAttribute() はこのアサーションの逆で、同じ引数をとります。
例 22.5: assertClassHasStaticAttribute() の使用法
<?php
class ClassHasStaticAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertClassHasStaticAttribute('foo', 'stdClass');
}
}
?>
phpunit ClassHasStaticAttributeTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) ClassHasStaticAttributeTest::testFailure
Failed asserting that class "stdClass" has static attribute "foo".
/home/sb/ClassHasStaticAttributeTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertContains(mixed $needle, Iterator|array $haystack[, string $message = ''])
$needle が $haystack の要素でない場合にエラー $message を報告します。
assertNotContains() はこのアサーションの逆で、同じ引数をとります。
assertAttributeContains() と assertAttributeNotContains() は便利なラッパーで、クラスやオブジェクトの public、protected、private 属性を haystack として使用することができます。
例 22.6: assertContains() の使用法
<?php
class ContainsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContains(4, array(1, 2, 3));
}
}
?>
phpunit ContainsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) ContainsTest::testFailure
Failed asserting that an array contains <integer:4>.
/home/sb/ContainsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertContains(string $needle, string $haystack[, string $message = ''])
$needle が $haystack の部分文字列でない場合にエラー $message を報告します。
例 22.7: assertContains() の使用法
<?php
class ContainsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContains('baz', 'foobar');
}
}
?>
phpunit ContainsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) ContainsTest::testFailure
Failed asserting that <string:foobar> contains "baz".
/home/sb/ContainsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertContainsOnly(string $type, Iterator|array $haystack[, boolean $isNativeType = NULL, string $message = ''])
$haystack の中身の型が $type だけではない場合にエラー $message を報告します。
$isNativeType はフラグで、$type がネイティブな PHP の型であるかどうかを表します。
assertNotContainsOnly() はこのアサーションの逆で、同じ引数をとります。
assertAttributeContainsOnly() と assertAttributeNotContainsOnly() は便利なラッパーで、クラスやオブジェクトの public、protected、private 属性を実際の値として使用することができます。
例 22.8: assertContainsOnly() の使用法
<?php
class ContainsOnlyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContainsOnly('string', array('1', '2', 3));
}
}
?>
phpunit ContainsOnlyTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) ContainsOnlyTest::testFailure
Failed asserting that
Array
(
[0] => 1
[1] => 2
[2] => 3
)
contains only values of type "string".
/home/sb/ContainsOnlyTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertEqualXMLStructure(DOMNode $expectedNode, DOMNode $actualNode[, boolean $checkAttributes = FALSE, string $message = ''])
XXX
assertEquals(mixed $expected, mixed $actual[, string $message = ''])
2 つの変数 $expected と $actual が等しくない場合にエラー $message を報告します。
assertNotEquals() はこのアサーションの逆で、同じ引数をとります。
assertAttributeEquals() と assertAttributeNotEquals() は便利なラッパーで、クラスやオブジェクトの public、protected、private 属性を実際の値として使用することができます。
例 22.10: assertEquals() の使用法
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertEquals(1, 0);
}
public function testFailure2()
{
$this->assertEquals('bar', 'baz');
}
public function testFailure3()
{
$this->assertEquals("foo\nbar\nbaz\n", "foo\nbah\nbaz\n");
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
FFF
Time: 0 seconds
There were 3 failures:
1) EqualsTest::testFailure
Failed asserting that <integer:0> matches expected value <integer:1>.
/home/sb/EqualsTest.php:11
2) EqualsTest::testFailure2
Failed asserting that two strings are equal.
expected string <bar>
difference < x>
got string <baz>
/home/sb/EqualsTest.php:16
3) EqualsTest::testFailure3
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,3 +1,3 @@
foo
-bar
+bah
baz
/home/sb/EqualsTest.php:21
FAILURES!
Tests: 3, Assertions: 3, Failures: 3.
引数 $expected と $actual の型により特化した比較については、以下を参照ください。
assertEquals(float $expected, float $actual[, string $message = '', float $delta = 0])
2 つの float 値 $expected と $actual の誤差が $delta より大きい場合にエラー $message を報告します。
なぜ $delta が必要となるのかについては comparing floating-point numbers を参照ください。
例 22.11: float 値での assertEquals() の使用法
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testSuccess()
{
$this->assertEquals(1.0, 1.1, '', 0.2);
}
public function testFailure()
{
$this->assertEquals(1.0, 1.1);
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
.F
Time: 0 seconds
There was 1 failure:
1) EqualsTest::testFailure
Failed asserting that <double:1.1> matches expected value <double:1>.
/home/sb/EqualsTest.php:11
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
assertEquals(DOMDocument $expected, DOMDocument $actual[, string $message = ''])
2 つの DOMDocument オブジェクト $expected と $actual で表される XML ドキュメントが (コメントを除去して正規化した状態で) 等しくない場合にエラー $message を報告します。
例 22.12: DOMDocument オブジェクトでの assertEquals() の使用法
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$expected = new DOMDocument;
$expected->loadXML('<foo><bar/></foo>');
$actual = new DOMDocument;
$actual->loadXML('<bar><foo/></bar>');
$this->assertEquals($expected, $actual);
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) EqualsTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
-<foo>
- <bar/>
-</foo>
+<bar>
+ <foo/>
+</bar>
/home/sb/EqualsTest.php:12
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertEquals(object $expected, object $actual[, string $message = ''])
2 つのオブジェクト $expected と $actual が同じ属性値を持たない場合にエラー $message を報告します。
例 22.13: オブジェクトでの assertEquals() の使用法
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$expected = new stdClass;
$expected->foo = 'foo';
$expected->bar = 'bar';
$actual = new stdClass;
$actual->foo = 'bar';
$actual->baz = 'bar';
$this->assertEquals($expected, $actual);
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) EqualsTest::testFailure
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ -1,5 +1,5 @@
stdClass Object
(
- [foo] => foo
- [bar] => bar
+ [foo] => bar
+ [baz] => bar
)
/home/sb/EqualsTest.php:14
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertEquals(array $expected, array $actual[, string $message = ''])
2 つの配列 $expected と $actual が等しくない場合にエラー $message を報告します。
例 22.14: 配列での assertEquals() の使用法
<?php
class EqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertEquals(array('a', 'b', 'c'), array('a', 'c', 'd'));
}
}
?>
phpunit EqualsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) EqualsTest::testFailure
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ -1,6 +1,6 @@
Array
(
[0] => a
- [1] => b
- [2] => c
+ [1] => c
+ [2] => d
)
/home/sb/EqualsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertFalse(bool $condition[, string $message = ''])
$condition が TRUE の場合にエラー $message を報告します。
例 22.15: assertFalse() の使用法
<?php
class FalseTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFalse(TRUE);
}
}
?>
phpunit FalseTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) FalseTest::testFailure
Failed asserting that <boolean:true> is false.
/home/sb/FalseTest.php:11
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertFileEquals(string $expected, string $actual[, string $message = ''])
$expected で指定したファイルと $actual で指定したファイルの内容が異なる場合にエラー $message を報告します。
assertFileNotEquals() はこのアサーションの逆で、同じ引数をとります。
例 22.16: assertFileEquals() の使用法
<?php
class FileEqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFileEquals('/home/sb/expected', '/home/sb/actual');
}
}
?>
phpunit FileEqualsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) FileEqualsTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,2 +1,2 @@
-expected
+actual
/home/sb/FileEqualsTest.php:6
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.
assertFileExists(string $filename[, string $message = ''])
ファイル $filename が存在しない場合にエラー $message を報告します。
assertFileNotExists() はこのアサーションの逆で、同じ引数をとります。
例 22.17: assertFileExists() の使用法
<?php
class FileExistsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFileExists('/path/to/file');
}
}
?>
phpunit FileExistsTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) FileExistsTest::testFailure
Failed asserting that file "/path/to/file" exists.
/home/sb/FileExistsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertGreaterThan(mixed $expected, mixed $actual[, string $message = ''])
$actual の値が $expected の値より大きくない場合にエラー $message を報告します。
assertAttributeGreaterThan() は便利なラッパーで、クラスやオブジェクトの public、protected、private 属性を実際の値として使用することができます。
例 22.18: assertGreaterThan() の使用法
<?php
class GreaterThanTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertGreaterThan(2, 1);
}
}
?>
phpunit GreaterThanTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) GreaterThanTest::testFailure
Failed asserting that <integer:1> is greater than <integer:2>.
/home/sb/GreaterThanTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertGreaterThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])
$actual の値が $expected の値以上でない場合にエラー $message を報告します。
assertAttributeGreaterThanOrEqual() は便利なラッパーで、クラスやオブジェクトの public、protected、private 属性を実際の値として使用することができます。
例 22.19: assertGreaterThanOrEqual() の使用法
<?php
class GreatThanOrEqualTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertGreaterThanOrEqual(2, 1);
}
}
?>
phpunit GreaterThanOrEqualTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) GreatThanOrEqualTest::testFailure
Failed asserting that <integer:1> is equal to <integer:2> or is greater than <integer:2>.
/home/sb/GreaterThanOrEqualTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertLessThan(mixed $expected, mixed $actual[, string $message = ''])
$actual の値が $expected の値より小さくない場合にエラー $message を報告します。
assertAttributeLessThan() は便利なラッパーで、クラスやオブジェクトの public、protected、private 属性を実際の値として使用することができます。
例 22.20: assertLessThan() の使用法
<?php
class LessThanTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertLessThan(1, 2);
}
}
?>
phpunit LessThanTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) LessThanTest::testFailure
Failed asserting that <integer:2> is less than <integer:1>.
/home/sb/LessThanTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertLessThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])
$actual の値が $expected の値以下でない場合にエラー $message を報告します。
assertAttributeLessThanOrEqual() は便利なラッパーで、クラスやオブジェクトの public、protected、private 属性を実際の値として使用することができます。
例 22.21: assertLessThanOrEqual() の使用法
<?php
class LessThanOrEqualTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertLessThanOrEqual(1, 2);
}
}
?>
phpunit LessThanOrEqualTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) LessThanOrEqualTest::testFailure
Failed asserting that <integer:2> is equal to <integer:1> or is less than <integer:1>.
/home/sb/LessThanOrEqualTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
$variable が NULL でないときにエラー $message を報告します。
assertNotNull() はこのアサーションの逆で、同じ引数をとります。
例 22.22: assertNull() の使用法
<?php
class NullTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertNull('foo');
}
}
?>
phpunit NotNullTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) NullTest::testFailure
Failed asserting that <string:foo> is null.
/home/sb/NullTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertObjectHasAttribute(string $attributeName, object $object[, string $message = ''])
$object->attributeName が存在しない場合にエラー $message を報告します。
assertObjectNotHasAttribute() はこのアサーションの逆で、同じ引数をとります。
例 22.23: assertObjectHasAttribute() の使用法
<?php
class ObjectHasAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertObjectHasAttribute('foo', new stdClass);
}
}
?>
phpunit ObjectHasAttributeTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) ObjectHasAttributeTest::testFailure
Failed asserting that object of class "stdClass" has attribute "foo".
/home/sb/ObjectHasAttributeTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertRegExp(string $pattern, string $string[, string $message = ''])
$string が正規表現 $pattern にマッチしない場合にエラー $message を報告します。
assertNotRegExp() はこのアサーションの逆で、同じ引数をとります。
例 22.24: assertRegExp() の使用法
<?php
class RegExpTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertRegExp('/foo/', 'bar');
}
}
?>
phpunit RegExpTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) RegExpTest::testFailure
Failed asserting that <string:bar> matches PCRE pattern "/foo/".
/home/sb/RegExpTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertSame(mixed $expected, mixed $actual[, string $message = ''])
2 つの変数 $expected と $actual が同じ型・同じ値でない場合にエラー $message を報告します。
assertNotSame() はこのアサーションの逆で、同じ引数をとります。
assertAttributeSame() と assertAttributeNotSame() は便利なラッパーで、クラスやオブジェクトの public、protected、private 属性を実際の値として使用することができます。
例 22.25: assertSame() の使用法
<?php
class SameTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertSame('2204', 2204);
}
}
?>
phpunit SameTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) SameTest::testFailure
<integer:2204> does not match expected type "string".
/home/sb/SameTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertSame(object $expected, object $actual[, string $message = ''])
2 つの変数 $expected と $actual が同じオブジェクトを参照していない場合にエラー $message を報告します。
例 22.26: オブジェクトでの assertSame() の使用法
<?php
class SameTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertSame(new stdClass, new stdClass);
}
}
?>
phpunit SameTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) SameTest::testFailure
Failed asserting that two variables reference the same object.
/home/sb/SameTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertSelectCount(array $selector, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])
XXX
assertSelectEquals(array $selector, string $content, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])
XXX
assertSelectRegExp(array $selector, string $pattern, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])
XXX
assertStringEndsWith(string $suffix, string $string[, string $message = ''])
$string が $suffix で終わっていない場合にエラー $message を報告します。
assertStringEndsNotWith() はこのアサーションの逆で、同じ引数をとります。
例 22.30: assertStringEndsWith() の使用法
<?php
class StringEndsWithTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringEndsWith('suffix', 'foo');
}
}
?>
phpunit StringEndsWithTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) StringEndsWithTest::testFailure
Failed asserting that <string:foo> ends with "suffix".
/home/sb/StringEndsWithTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertStringEqualsFile(string $expectedFile, string $actualString[, string $message = ''])
$expectedFile で指定したファイルの内容に $actualString が含まれない場合にエラー $message を報告します。
assertStringNotEqualsFile() はこのアサーションの逆で、同じ引数をとります。
例 22.31: assertStringEqualsFile() の使用法
<?php
class StringEqualsFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringEqualsFile('/home/sb/expected', 'actual');
}
}
?>
phpunit StringEqualsFileTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) StringEqualsFileTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,2 +1 @@
-expected
-
+actual
\ No newline at end of file
/home/sb/StringEqualsFileTest.php:6
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
assertStringStartsWith(string $prefix, string $string[, string $message = ''])
$string が $prefix で始まっていない場合にエラー $message を報告します。
assertStringStartsNotWith() はこのアサーションの逆で、同じ引数をとります。
例 22.32: assertStringStartsWith() の使用法
<?php
class StringStartsWithTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringStartsWith('prefix', 'foo');
}
}
?>
phpunit StringStartsWithTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) StringStartsWithTest::testFailure
Failed asserting that <string:foo> starts with "prefix".
/home/sb/StringStartsWithTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertTag(array $matcher, string $actual[, string $message = '', boolean $isHtml = TRUE])
$actual が $matcher にマッチしない場合にエラー $message を報告します。
$matcher は連想配列で、アサーションに使用するマッチ条件を指定します。
id: 指定した id 属性のノードが対応する値にマッチすること。
tags: ノードの型が対応する値にマッチすること。
attributes: ノードの属性が、対応する値の連想配列 $attributes にマッチすること。
content: テキストの内容が指定した値にマッチすること。
parent: ノードの親が連想配列 $parent にマッチすること。
child: ノードの直接の子のうち少なくともひとつが連想配列 $child の条件を満たすこと。
ancestor: ノードの先祖のうちの少なくともひとつが連想配列 $ancestor の条件を満たすこと。
descendant: ノードの子孫のうちの少なくともひとつが連想配列 $descendant の条件を満たすこと。
children: ノードの子の数を数えるための連想配列。
count: マッチする子の数がこの数に等しいこと。
less_than: マッチする子の数がこの数より少ないこと。
greater_than: マッチする子の数がこの数より多いこと。
only: 連想配列で子のマッチに使用するキーを指定し、それにマッチした子のみを数える。
assertNotTag() はこのアサーションの逆で、同じ引数をとります。
例 22.33: assertTag() の使用法
<?php
// id="my_id" という要素があることを表明する matcher
$matcher = array('id' => 'my_id');
// "span" タグが存在することを表明する matcher
$matcher = array('tag' => 'span');
// 中身が "Hello World" である "span" タグが存在することを表明する
// matcher
$matcher = array('tag' => 'span', 'content' => 'Hello World');
// 正規表現で指定した内容にマッチする中身を持つ "span" タグが
// 存在することを表明する matcher
$matcher = array('tag' => 'span', 'content' => '/Try P(HP|ython)/');
// class 属性に "list" が指定された "span" タグが存在することを表明する matcher
$matcher = array(
'tag' => 'span',
'attributes' => array('class' => 'list')
);
// "span" が "div" の内部に存在することを表明する matcher
$matcher = array(
'tag' => 'span',
'parent' => array('tag' => 'div')
);
// "span" が "table" 内のどこかに存在することを表明する matcher
$matcher = array(
'tag' => 'span',
'ancestor' => array('tag' => 'table')
);
// 子要素に少なくともひとつの "em" を持つ "span" が存在することを表明する matcher
$matcher = array(
'tag' => 'span',
'child' => array('tag' => 'em')
);
// "span" の中 (何段階か下でも可) に
// "strong" タグが存在することを表明する matcher
$matcher = array(
'tag' => 'span',
'descendant' => array('tag' => 'strong')
);
// 直接の子として 5 から 10 の "em" タグを持つ "span"
// が存在することを表明する matcher
$matcher = array(
'tag' => 'span',
'children' => array(
'less_than' => 11,
'greater_than' => 4,
'only' => array('tag' => 'em')
)
);
// "div" というタグが存在し、先祖に "ul" そして直接の親に "li"
// (class="enum") を持つこと、そして id="my_test" で中身が
// "Hello World" である "span" を子孫にもつことを表明する matcher
$matcher = array(
'tag' => 'div',
'ancestor' => array('tag' => 'ul'),
'parent' => array(
'tag' => 'li',
'attributes' => array('class' => 'enum')
),
'descendant' => array(
'tag' => 'span',
'child' => array(
'id' => 'my_test',
'content' => 'Hello World'
)
)
);
// assertTag() を使用して、$matcher を $html に適用します
$this->assertTag($matcher, $html);
// assertTag() を使用して、$matcher を $xml に適用します
$this->assertTag($matcher, $xml, '', FALSE);
?>
もっと複雑なアサーションを行う場合には、 PHPUnit_Framework_Constraint クラスを使用します。 これらは、assertThat() メソッドを使用して評価されます。 例 22.34 は、 logicalNot() と equalTo() を用いて assertNotEquals() と同じアサーションを行う方法を示すものです。
assertThat(mixed $value, PHPUnit_Framework_Constraint $constraint[, $message = ''])
$value が $constraint にマッチしない場合にエラー $message を報告します。
例 22.34: assertThat() の使用法
<?php
class BiscuitTest extends PHPUnit_Framework_TestCase
{
public function testEquals()
{
$theBiscuit = new Biscuit('Ginger');
$myBiscuit = new Biscuit('Ginger');
$this->assertThat(
$theBiscuit,
$this->logicalNot(
$this->equalTo($myBiscuit)
)
);
}
}
?>
表 22.1 に、 使用できる PHPUnit_Framework_Constraint クラスをまとめます。
表22.1 制約
| 制約 | 意味 |
|---|---|
PHPUnit_Framework_Constraint_Attribute attribute(PHPUnit_Framework_Constraint $constraint, $attributeName)
|
別の制約を、クラスあるいはオブジェクトの属性として適用する制約。 |
PHPUnit_Framework_Constraint_IsAnything anything()
|
あらゆる入力値を受け入れる制約。 |
PHPUnit_Framework_Constraint_ArrayHasKey arrayHasKey(mixed $key)
|
配列が指定したキーを保持していることを保証する制約。 |
PHPUnit_Framework_Constraint_TraversableContains contains(mixed $value)
|
Iterator インターフェイスを実装している array やオブジェクトが、指定した値を保持していることを保証する制約。
|
PHPUnit_Framework_Constraint_IsEqual equalTo($value, $delta = 0, $maxDepth = 10)
|
ある値が別の値と等しいかどうかを調べる制約。 |
PHPUnit_Framework_Constraint_Attribute attributeEqualTo($attributeName, $value, $delta = 0, $maxDepth = 10)
|
ある値がクラスあるいはオブジェクトの属性と等しいかどうかを調べる制約。 |
PHPUnit_Framework_Constraint_FileExists fileExists()
|
指定した名前のファイルが存在するかどうかを調べる制約。 |
PHPUnit_Framework_Constraint_GreaterThan greaterThan(mixed $value)
|
評価される値が、指定した値より大きいことを保証する制約。 |
PHPUnit_Framework_Constraint_Or greaterThanOrEqual(mixed $value)
|
評価される値が、指定した値以上であることを保証する制約。 |
PHPUnit_Framework_Constraint_ClassHasAttribute classHasAttribute(string $attributeName)
|
評価されるクラスに、指定した属性があることを保証する制約。 |
PHPUnit_Framework_Constraint_ClassHasStaticAttribute classHasStaticAttribute(string $attributeName)
|
評価されるクラスに、指定した static 属性があることを保証する制約。 |
PHPUnit_Framework_Constraint_ObjectHasAttribute hasAttribute(string $attributeName)
|
評価されるオブジェクトが、指定した属性を保持していることを保証する制約。 |
PHPUnit_Framework_Constraint_IsIdentical identicalTo(mixed $value)
|
ある値が別の値と同一であることを保証する制約。 |
PHPUnit_Framework_Constraint_IsFalse isFalse()
|
評価される値が FALSE であることを保証する制約。
|
PHPUnit_Framework_Constraint_IsInstanceOf isInstanceOf(string $className)
|
評価されるオブジェクトが、指定したクラスのインスタンスであることを保証する制約。 |
PHPUnit_Framework_Constraint_IsNull isNull()
|
評価される値が NULL であることを保証する制約。
|
PHPUnit_Framework_Constraint_IsTrue isTrue()
|
評価される値が TRUE であることを保証する制約。
|
PHPUnit_Framework_Constraint_IsType isType(string $type)
|
評価される値が、指定した型であることを保証する制約。 |
PHPUnit_Framework_Constraint_LessThan lessThan(mixed $value)
|
評価される値が、指定した値より小さいことを保証する制約。 |
PHPUnit_Framework_Constraint_Or lessThanOrEqual(mixed $value)
|
評価される値が、指定した値以下であることを保証する制約。 |
logicalAnd()
|
論理積 (AND)。 |
logicalNot(PHPUnit_Framework_Constraint $constraint)
|
論理否定 (NOT)。 |
logicalOr()
|
論理和 (OR)。 |
logicalXor()
|
排他的論理和 (XOR)。 |
PHPUnit_Framework_Constraint_PCREMatch matchesRegularExpression(string $pattern)
|
評価される文字列が、正規表現にマッチすることを保証する制約。 |
PHPUnit_Framework_Constraint_StringContains stringContains(string $string, bool $case)
|
評価される文字列が、指定した文字列を含むことを保証する制約。 |
PHPUnit_Framework_Constraint_StringEndsWith stringEndsWith(string $suffix)
|
評価される文字列が、指定したサフィックスで終わることを保証する制約。 |
PHPUnit_Framework_Constraint_StringStartsWith stringStartsWith(string $prefix)
|
評価される文字列が、指定したプレフィックスで始まることを保証する制約。 |
assertTrue(bool $condition[, string $message = ''])
$condition が FALSE の場合にエラー $message を報告します。
例 22.35: assertTrue() の使用法
<?php
class TrueTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertTrue(FALSE);
}
}
?>
phpunit TrueTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) TrueTest::testFailure
Failed asserting that <boolean:false> is true.
/home/sb/TrueTest.php:11
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertType(string $expected, mixed $actual[, string $message = ''])
変数 $actual の型が $expected でない場合にエラー $message を報告します。
$expected はこれらの定数のいずれかとなります。
PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY ("array")
PHPUnit_Framework_Constraint_IsType::TYPE_BOOL ("bool")
PHPUnit_Framework_Constraint_IsType::TYPE_FLOAT ("float")
PHPUnit_Framework_Constraint_IsType::TYPE_INT ("int")
PHPUnit_Framework_Constraint_IsType::TYPE_NULL ("null")
PHPUnit_Framework_Constraint_IsType::TYPE_NUMERIC ("numeric")
PHPUnit_Framework_Constraint_IsType::TYPE_OBJECT ("object")
PHPUnit_Framework_Constraint_IsType::TYPE_RESOURCE ("resource")
PHPUnit_Framework_Constraint_IsType::TYPE_STRING ("string")
assertNotType() はこのアサーションの逆で、同じ引数をとります。
例 22.36: assertType() の使用法
<?php
class TypeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertType(PHPUnit_Framework_Constraint_IsType::TYPE_STRING, 2204);
}
public function testFailure2()
{
$this->assertType('string', 2204);
}
public function testFailure3()
{
$this->assertType('Exception', new stdClass);
}
}
?>
phpunit TypeTest
PHPUnit 3.4.4 by Sebastian Bergmann.
FFF
Time: 0 seconds
There were 3 failures:
1) TypeTest::testFailure
Failed asserting that <integer:2204> is of type "string".
/home/sb/TypeTest.php:6
2) TypeTest::testFailure2
Failed asserting that <integer:2204> is of type "string".
/home/sb/TypeTest.php:11
3) TypeTest::testFailure3
Failed asserting that <stdClass> is an instance of class "Exception".
/home/sb/TypeTest.php:16
FAILURES!
Tests: 3, Assertions: 3, Failures: 3.
assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile[, string $message = ''])
$actualFile の XML ドキュメントが $expectedFile の XML ドキュメントと異なる場合にエラー $message を報告します。
assertXmlFileNotEqualsXmlFile() はこのアサーションの逆で、同じ引数をとります。
例 22.37: assertXmlFileEqualsXmlFile() の使用法
<?php
class XmlFileEqualsXmlFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlFileEqualsXmlFile(
'/home/sb/expected.xml', '/home/sb/actual.xml');
}
}
?>
phpunit XmlFileEqualsXmlFileTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) XmlFileEqualsXmlFileTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
<foo>
- <bar/>
+ <baz/>
</foo>
/home/sb/XmlFileEqualsXmlFileTest.php:7
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.
assertXmlStringEqualsXmlFile(string $expectedFile, string $actualXml[, string $message = ''])
$actualXml の XML ドキュメントが $expectedFile の XML ドキュメントと異なる場合にエラー $message を報告します。
assertXmlStringNotEqualsXmlFile() はこのアサーションの逆で、同じ引数をとります。
例 22.38: assertXmlStringEqualsXmlFile() の使用法
<?php
class XmlStringEqualsXmlFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlStringEqualsXmlFile(
'/home/sb/expected.xml', '<foo><baz/></foo>');
}
}
?>
phpunit XmlStringEqualsXmlFileTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) XmlStringEqualsXmlFileTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
<foo>
- <bar/>
+ <baz/>
</foo>
/home/sb/XmlStringEqualsXmlFileTest.php:7
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
assertXmlStringEqualsXmlString(string $expectedXml, string $actualXml[, string $message = ''])
$actualXml の XML ドキュメントが $expectedXml の XML ドキュメントと異なる場合にエラー $message を報告します。
assertXmlStringNotEqualsXmlString() はこのアサーションの逆で、同じ引数をとります。
例 22.39: assertXmlStringEqualsXmlString() の使用法
<?php
class XmlStringEqualsXmlStringTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlStringEqualsXmlString(
'<foo><bar/></foo>', '<foo><baz/></foo>');
}
}
?>
phpunit XmlStringEqualsXmlStringTest
PHPUnit 3.4.4 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) XmlStringEqualsXmlStringTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
<foo>
- <bar/>
+ <baz/>
</foo>
/home/sb/XmlStringEqualsXmlStringTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
これら以外に、プロジェクトで使用している オブジェクト固有のアサーションが必要になることもあるでしょう。独自の Assert クラスを作成し、 そこに独自のアサーションを含めてテストに使用することができます。
アサーションに失敗すると、ボトルネックメソッド fail(string $message) がコールされ、これは PHPUnit_Framework_AssertionFailedError をスローします。 このメソッドにもパラメータなしのものがあります。テストでエラーが発生した際に、 fail() を明示的にコールします。 例外が発生することが期待されるテストなどがその例になります。 表 22.2 に、PHPUnit のボトルネックメソッドをまとめます。
markTestIncomplete() および markTestSkipped() は、テストに対して「未完了」あるいは「省略」の印をつけるために便利なメソッドです。
表22.3 テストに対して「未完了」あるいは「省略」の印をつける
| メソッド | 意味 |
|---|---|
void markTestIncomplete(string $message)
|
現在のテストに「未完了」の印をつけます。$message はオプションです。
|
void markTestSkipped(string $message)
|
現在のテストに「省略」の印をつけます。$message はオプションです。
|
単体テストとは、もともとクラスの公開インターフェイスをテストするものです。 しかし、時には非公開の属性の内容をテストしたいこともあるでしょう。 readAttribute() メソッドを使用すると、 指定したオブジェクトの属性の値を取得することができます。
表22.4 非公開属性へのアクセス
| メソッド | 意味 |
|---|---|
Mixed readAttribute($object, $attributeName)
|
オブジェクトの指定した属性 ($attributeName) の値を返します。protected あるいは private である属性についても動作します。
|
PHPUnit_Framework_Test は、 テストとして働くすべてのオブジェクトが使用する、 一般的なインターフェイスです。これを実装したオブジェクトは、 ひとつあるいは複数のテストを表すことになります。 表 22.5 に示す 2 つのメソッドが定義されています。
表22.5 実装することになるメソッド
| メソッド | 意味 |
|---|---|
int count()
|
テストの数を返します。 |
void run(PHPUnit_Framework_TestResult $result)
|
テストを実行し、結果を $result で報告します。
|
PHPUnit_Framework_Test の実装クラスとして有名なのは、 PHPUnit_Framework_TestCase および PHPUnit_Framework_TestSuite の 2 つです。 PHPUnit_Framework_Test を実装したクラスを独自に作成することも可能です。 このインターフェイスはあえて小規模に設計されているので、実装するのは簡単でしょう。
テストケースクラスは PHPUnit_Framework_TestCase クラスを継承して作成します。たいていの場合は、 テストスイートから自動的にテストを実行させることになるでしょう。 この場合、(規約により) 各テストは test* という名前のメソッドにしておかなければなりません。
PHPUnit_Framework_TestCase は PHPUnit_Framework_Test::countTestCases() を実装しており、 これは常に 1 を返します。このクラスで実装されている PHPUnit_Framework_Test::run(PHPUnit_Framework_TestResult $result) は、まず setUp() を実行し、テストメソッドを実行し、 それから tearDown() を実行し、その結果を PHPUnit_Framework_TestResult に報告します。
PHPUnit_Framework_TestCase によって実装されているメソッドを 表 22.6 にまとめます。
表22.6 TestCase
| メソッド | 意味 |
|---|---|
__construct()
|
テストケースを作成します。 |
__construct(string $name)
|
指定した名前のテストケースを作成します。この名前はテストケースを表示する際に使用されます。また、リフレクションで取得するテストメソッドの名前としても使用されます。 |
string getName()
|
テストケースの名前を返します。 |
void setName($name)
|
テストケースの名前を設定します。 |
PHPUnit_Framework_TestResult run(PHPUnit_Framework_TestResult $result)
|
テストケースを実行し、結果を $result に格納するための便利なメソッドです。
|
void runTest()
|
リフレクションによってテストメソッドを実行されたくない場合に、テストメソッドをオーバーライドします。 |
object getMock($originalClassName, [array $methods, [array $arguments, [string $mockClassName, [boolean $callOriginalConstructor, [boolean $callOriginalClone, [boolean $callAutoload]]]]]])
|
指定した $originalClassName 用のモックオブジェクト (第 11 章 を参照ください) を返します。 デフォルトでは、指定したクラスの全メソッドのモックが作成されます。 二番目の (オプションの) パラメータを指定すると、 その配列の要素と一致する名前のメソッドについてのみモックが作成されます。 三番目の (オプションの) パラメータには、 モックオブジェクトのコンストラクタに渡すパラメータを配列で指定します。 四番目の (オプションの) パラメータを使用すると、 モックオブジェクトのクラス名を指定することができます。 五番目の (オプションの) パラメータを使用すると、 元のオブジェクトの __construct() メソッドをコールしないようにすることができます。 六番目の (オプションの) パラメータを使用すると、 元のオブジェクトの __clone() メソッドをコールしないようにすることができます。 七番目の (オプションの) パラメータを使用すると、 モックオブジェクトの作成時に __autoload() を無効にすることができます。
|
object getMockForAbstractClass($originalClassName, [array $arguments, [string $mockClassName, [boolean $callOriginalConstructor, [boolean $callOriginalClone, [boolean $callAutoload]]]]])
|
指定した抽象クラス $originalClassName 用のモックオブジェクト (第 11 章 を参照ください) を返します。 指定した抽象クラスの全抽象メソッドのモックが作成されます。 これにより、抽象クラスの具象メソッドをテストできるようになります。
|
object getMockFromWsdl($wsdlFile, [string $originalClassName, [string $mockClassName, [array $methods, [boolean $callOriginalConstructor)
|
$wsdlFile で指定した SOAP ウェブサービス用のモックオブジェクト (第 11 章 を参照ください) を返します。
|
void iniSet(string $varName, mixed $newValue)
|
このメソッドは ini_set() 関数のラッパーです。テストが終了すると、php.ini の設定を自動的にもとの値に戻します。
|
void setLocale(integer $category, string $locale, ...)
|
このメソッドは setlocale() 関数のラッパーです。テストが終了すると、自動的にもとの設定値に戻します。
|
このクラスには、ふたつのテンプレートメソッド setUp() および tearDown() が存在します。これをオーバーライドすると、 実行しようとしているテストに関する前処理や後始末を行うことができます。 表 22.7 にこれらのメソッドをまとめます。 テンプレートメソッド assertPreConditions() および assertPostConditions() を使用すると、 テストケースクラス内のすべてのテストで実行するアサーションを定義することができます。
表22.7 テンプレートメソッド
| メソッド | 意味 |
|---|---|
void setUp()
|
これをオーバーライドして、fixture の準備、たとえばオブジェクトグラフの作成などを行います。 |
void assertPreConditions()
|
これをオーバーライドして、テストケースクラス内のすべてのテストで共有するアサーションを実行します。このメソッドがコールされるのは、テストの実行が始まる前に setUp() がコールされた後です。 |
void assertPostConditions()
|
これをオーバーライドして、テストケースクラス内のすべてのテストで共有するアサーションを実行します。このメソッドがコールされるのは、テストの実行が終わる前に tearDown() がコールされる前です。 |
void tearDown()
|
これをオーバーライドして、fixture の後始末、たとえばオブジェクトグラフの削除などを行います。 |
PHPUnit_Framework_TestSuite は複数の PHPUnit_Framework_Test を組み合わせたものです。 簡単に言うと、このクラスには複数のテストケースが含まれており、 テストスイートを実行するとそれらの全てのテストが実行されます。 テストスイートは composite なので、テストスイートの中に別のテストスイートを含め、 さらにそのテストスイートの中には別のテストスイートが含まれており…… といったことも可能です。これにより、 いろいろなところから集めたテストをひとまとめにすることが簡単になります。
run(PHPUnit_Framework_TestResult $result) および countTestCases() の 2 つに加え、 PHPUnit_Framework_TestSuite は名前つきインスタンス、 名前なしインスタンスを作成するためのメソッドも用意しています。 PHPUnit_Framework_TestSuite のインスタンスを作成するためのメソッドを 表 22.8 に示します。
表22.8 名前つき、あるいは名前なしインスタンスの作成
| メソッド | 意味 |
|---|---|
__construct()
|
空のテストスイートを返します。 |
__construct(string $theClass)
|
test* という名前のメソッドを持つ、$theClass という名前のクラスのインスタンスを含むテストスイートを返します。$theClass という名前のクラスが存在しない場合は、$theClass という名前の空のテストスイートが返されます。
|
__construct(string $theClass, string $name)
|
test* という名前のメソッドを持つ $theClass という名前のクラスのインスタンスを含む、$name という名前のテストスイートを返します。
|
__construct(ReflectionClass $theClass)
|
test* という名前のメソッドを持つ、$theClass が指すクラスのインスタンスを含むテストスイートを返します。
|
__construct(ReflectionClass $theClass, $name)
|
test* という名前のメソッドを持つ $theClass が指すクラスのインスタンスを含む、$name という名前のテストスイートを返します。
|
string getName()
|
テストスイートの名前を返します。 |
void setName(string $name)
|
テストスイートの名前を設定します。 |
void markTestSuiteSkipped(string $message)
|
現在処理中のテストスイートを、処理をスキップするように設定します。$message はオプションです。
|
PHPUnit_Framework_TestSuite には、 PHPUnit_Framework_Test を追加したり取得したりするためのメソッドも用意されています。これを 表 22.9 にまとめます。
表22.9 テストの追加、取得
| メソッド | 意味 |
|---|---|
void addTestSuite(PHPUnit_Framework_TestSuite $suite)
|
別のテストスイートを、このテストスイートに追加します。 |
void addTestSuite(string $theClass)
|
test* という名前のテストメソッドを持つ $theClass という名前のクラスのインスタンスを含むテストスイートを、このテストスイートに追加します。
|
void addTestSuite(ReflectionClass $theClass)
|
test* という名前のテストメソッドを持つ $theClass で表されるクラスのインスタンスを含むテストスイートを、このテストスイートに追加します。
|
void addTest(PHPUnit_Framework_Test $test)
|
テストスイートに $test を追加します。
|
void addTestFile(string $filename)
|
指定したソースファイルで定義されているクラスをテストスイートに追加します。 |
void addTestFiles(array $filenames)
|
指定したソースファイルで定義されているクラスをテストスイートに追加します。 |
int testCount()
|
このテストスイートに直接登録されているテストの数を返します (再帰的には検索しません)。 |
PHPUnit_Framework_Test[] tests()
|
このテストスイートに直接登録されているテストを返します。 |
PHPUnit_Framework_Test testAt(int $index)
|
$index 番目のテストを返します。
|
例 22.40 に、テストスイートを作成して実行する方法を示します。
例 22.40: テストスイートの作成および実行
<?php
require_once 'PHPUnit/Framework.php';
require_once 'ArrayTest.php';
// ArrayTest クラスのテストを含む
// テストスイートを作成します。
$suite = new PHPUnit_Framework_TestSuite('ArrayTest');
// テストを実行します。
$suite->run();
?>
第 7 章 では、 PHPUnit_Framework_TestSuite クラスを使用して 階層化されたテストケースを組み合わせる例を示します。
PHPUnit_Framework_TestSuite クラスには、 ふたつのテンプレートメソッド setUp() および tearDown() が存在します。 これらはそれぞれ、テストスイートのテストが実行される前と後にコールされます。
表22.10 テンプレートメソッド
| メソッド | 意味 |
|---|---|
void setUp()
|
テストスイートの最初のテストを実行する前にコールされます。 |
void tearDown()
|
テストスイートの最後のテストをコールした後でコールされます。 |
これらのテストを実行している間は、実行したテストの数・失敗したテスト・ テストの所要時間などをどこかに保存しておかなければなりません。 これらの結果を収集するのが PHPUnit_Framework_TestResult です。ひとつの PHPUnit_Framework_TestResult が、 テスト全体で使いまわされます。テストの実行結果や失敗の内容は PHPUnit_Framework_TestResult に記録されていき、 実行が終了すると、PHPUnit_Framework_TestResult には全てのテストの概要が含まれるようになります。
PHPUnit_Framework_TestResult は、 テストの進行状況を知りたい他のオブジェクトから参照されることもあります。 例えば、グラフィカルなテストランナーは PHPUnit_Framework_TestResult を監視し、各テストの開始時にプログレスバーを更新するでしょう。
表 22.11 は、 PHPUnit_Framework_TestResult の API をまとめたものです。
表22.11 TestResult
| メソッド | 意味 |
|---|---|
void addError(PHPUnit_Framework_Test $test, Exception $e)
|
実行中の $test から予期せぬ $e がスローされたことを記録します。
|
void addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e)
|
実行中の $test から予期せぬ $e がスローされたことを記録します。
|
PHPUnit_Framework_TestFailure[] errors()
|
記録されたエラーを返します。 |
PHPUnit_Framework_TestFailure[] failures()
|
記録された失敗を返します。 |
PHPUnit_Framework_TestFailure[] notImplemented()
|
記録された未完了テストを返します。 |
int errorCount()
|
記録されたエラーの数を返します。 |
int failureCount()
|
記録された失敗の数を返します。 |
int notImplementedCount()
|
未完了のテストケースの数を返します。 |
int count()
|
実行したテストケースの総数を返します。 |
boolean wasSuccessful()
|
すべてのテストの実行に成功したかどうかを返します。 |
boolean allCompletlyImplemented()
|
すべてのテストが完全に実装されているかどうかを返します。 |
void collectCodeCoverageInformation(bool $flag)
|
コードカバレッジ情報の収集を有効あるいは無効にします。 |
array getCodeCoverageInformation()
|
収集したコードカバレッジ情報を返します。 |
PHPUnit_Framework_TestResult のオブザーバを登録したい場合は、PHPUnit_Framework_TestListener を実装する必要があります。これを登録するには、 表 22.12 に示した addListener() を使用します。
表22.12 TestResult および TestListener
| メソッド | 意味 |
|---|---|
void addListener(PHPUnit_Framework_TestListener $listener)
|
$listener を登録し、テスト結果の内容が更新された場合にその内容を受け取るようにします。
|
void removeListener(PHPUnit_Framework_TestListener $listener)
|
更新を受け取る $listener の登録を解除します。
|
表 22.13 に、テストリスナーが実装するメソッドを示します。 例 23.3 も参照ください。
表22.13 TestListener のコールバック
| メソッド | 意味 |
|---|---|
void addError(PHPUnit_Framework_Test $test, Exception $e)
|
$test が $e をスローしました。
|
void addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e)
|
$test がアサーションに失敗し、PHPUnit_Framework_AssertionFailedError 系がスローされました。
|
void addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e)
|
$test は完了しませんでした。
|
void addSkippedTest(PHPUnit_Framework_Test $test, Exception $e)
|
$test は実行されませんでした。
|
void startTestSuite(PHPUnit_Framework_TestSuite $suite)
|
$suite の実行が始まります。
|
void endTestSuite(PHPUnit_Framework_TestSuite $suite)
|
$suite の実行が終了しました。
|
void startTest(PHPUnit_Framework_Test $test)
|
$test の実行が始まります。
|
void endTest(PHPUnit_Framework_Test $test)
|
$test の実行が終了しました。
|
| Prev | Next |
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertLessThan()
assertLessThanOrEqual()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertSame()
assertSelectCount()
assertSelectEquals()
assertSelectRegExp()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertTag()
assertThat()
assertTrue()
assertType()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
Copyright © 2005-2011 Sebastian Bergmann.