Prev Next

第4章 PHPUnit 用のテストの書き方

例 4.1 で、 PHP の配列操作のテストを PHPUnit 用に書く方法を示します。 この例では、PHPUnit を使ったテストを書く際の基本的な決まり事や手順を紹介します。

  1. Class という名前のクラスのテストは、ClassTest という名前のクラスに記述します。

  2. ClassTest は、(ほとんどの場合) PHPUnit_Framework_TestCase を継承します。

  3. テストは、test* という名前のパブリックメソッドとなります。

    あるいは、@test アノテーションをメソッドのコメント部で使用することで、それがテストメソッドであることを示すこともできます。

  4. テストメソッドの中で assertEquals() のようなアサーションメソッド (「アサーション」 を参照ください) を使用して、期待される値と実際の値が等しいことを確かめます。

例 4.1: PHPUnit での配列操作のテスト

<?php
class StackTest extends PHPUnit_Framework_TestCase
{
public function testPushAndPop()
{
$stack = array();
$this->assertEquals(0, count($stack));

array_push($stack, 'foo');
$this->assertEquals('foo', $stack[count($stack)-1]);
$this->assertEquals(1, count($stack));

$this->assertEquals('foo', array_pop($stack));
$this->assertEquals(0, count($stack));
}
}
?>

 

Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead.

何かを print 文やデバッガの式に書きたくなったときは、 代わりにその内容をテストに書くようにするんだ。

 
  --Martin Fowler

テストの依存性

 

Unit Tests are primarily written as a good practice to help developers identify and fix bugs, to refactor code and to serve as documentation for a unit of software under test. To achieve these benefits, unit tests ideally should cover all the possible paths in a program. One unit test usually covers one specific path in one function or method. However a test method is not necessary an encapsulated, independent entity. Often there are implicit dependencies between test methods, hidden in the implementation scenario of a test.

ユニットテストを書くそもそもの目的は、バグを発見と修正や コードのリファクタリングを開発者がやりやすくすること。 そしてテスト対象のソフトウェアのドキュメントとしての役割を果たすことだ。 これらの目的を達成するためには、 ユニットテストがプログラム内のすべてのルートをカバーしていることが理想である。 ひとつのユニットテストがカバーするのは、 通常はひとつの関数やメソッド内の特定のルートだけとなる。 しかし、テストメソッドは必ずしもカプセル化して独立させる必要はない。 複数のテストメソッドの間に暗黙の依存性があって、 隠された実装シナリオがテストの中にあるのもよくあることだ。

 
  --Adrian Kuhn et. al.

PHPUnit は、テストメソッド間の依存性の明示的な宣言をサポートしています。 この依存性とは、テストメソッドが実行される順序を定義するものではありません。 プロデューサーがテストフィクスチャを作ってそのインスタンスを返し、 依存するコンシューマーがそれを受け取って利用するというものです。

  • プロデューサーとは、返り値としてテスト対象のユニットを生成するテストメソッドのこと。

  • コンシューマーとは、プロデューサーの返り値に依存するテストメソッドのこと。

例 4.2 は、@depends アノテーションを使ってテストメソッドの依存性をあらわす例です。

例 4.2: @depends アノテーションを使った依存性の表現

<?php
class StackTest extends PHPUnit_Framework_TestCase
{
public function testEmpty()
{
$stack = array();
$this->assertEmpty($stack);

return $stack;
}

/**
* @depends testEmpty
*/
public function testPush(array $stack)
{
array_push($stack, 'foo');
$this->assertEquals('foo', $stack[count($stack)-1]);
$this->assertNotEmpty($stack);

return $stack;
}

/**
* @depends testPush
*/
public function testPop(array $stack)
{
$this->assertEquals('foo', array_pop($stack));
$this->assertEmpty($stack);
}
}
?>

上の例では、まず最初のテスト testEmpty() で新しい配列を作り、それが空であることを確かめます。 このテストは、フィクスチャを返します。 二番目のテスト testPush()testEmpty() に依存しており、 依存するテストの結果を引数として受け取ります。 最後の testPop()testPush() に依存しています。

問題の局所化を手早く行うには、失敗したテストに目を向けやすくしたいものです。 そのため PHPUnit では、 あるテストが失敗したときにはそのテストに依存する他のテストの実行をスキップします。 テスト間の依存性を活用して問題点を見つけやすくしている例を 例 4.3 に示します。

例 4.3: テストの依存性の活用

<?php
class DependencyFailureTest extends PHPUnit_Framework_TestCase
{
public function testOne()
{
$this->assertTrue(FALSE);
}

/**
* @depends testOne
*/
public function testTwo()
{
}
}
?>
phpunit --verbose DependencyFailureTest
PHPUnit 3.5.14 by Sebastian Bergmann.

FS

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) DependencyFailureTest::testOne
Failed asserting that <boolean:false> is true.

/home/sb/DependencyFailureTest.php:6

There was 1 skipped test:

1) DependencyFailureTest::testTwo
This test depends on "DependencyFailureTest::testOne" to pass.


FAILURES!
Tests: 1, Assertions: 1, Failures: 1, Skipped: 1.

ひとつのテストに複数の @depends アノテーションをつけることもできます。 PHPUnit はテストが実行される順序を変更しないので、 テストが実行されるときに確実に依存性が満たされているようにしておく必要があります。

データプロバイダ

テストメソッドには任意の引数を渡すことができます。 この引数は、データプロバイダメソッド (例 4.4provider()) で指定します。使用するデータプロバイダメソッドを指定するには @dataProvider アノテーションを使用します。

データプロバイダメソッドは、public でなければなりません。また、 メソッドの返り値の型は、配列の配列あるいはオブジェクト (Iterator インターフェイスを実装しており、 反復処理の際に配列を返すもの) である必要があります。 この返り値の各要素に対して、その配列の中身を引数としてテストメソッドがコールされます。

例 4.4: 配列の配列を返すデータプロバイダの使用

<?php
class DataTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider provider
*/
public function testAdd($a, $b, $c)
{
$this->assertEquals($c, $a + $b);
}

public function provider()
{
return array(
array(0, 0, 0),
array(0, 1, 1),
array(1, 0, 1),
array(1, 1, 3)
);
}
}
?>
phpunit DataTest
PHPUnit 3.5.14 by Sebastian Bergmann.

...F

Time: 0 seconds, Memory: 5.50Mb

There was 1 failure:

1) DataTest::testAdd with data set #3 (1, 1, 3)
Failed asserting that <integer:2> matches expected <integer:3>.

/home/sb/DataTest.php:9

FAILURES!
Tests: 4, Assertions: 4, Failures: 1.

例 4.5: Iterator オブジェクトを返すデータプロバイダの使用

<?php
require 'CsvFileIterator.php';

class DataTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider provider
*/
public function testAdd($a, $b, $c)
{
$this->assertEquals($c, $a + $b);
}

public function provider()
{
return new CsvFileIterator('data.csv');
}
}
?>
phpunit DataTest
PHPUnit 3.5.14 by Sebastian Bergmann.

...F

Time: 0 seconds, Memory: 5.50Mb

There was 1 failure:

1) DataTest::testAdd with data set #3 ('1', '1', '3')
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-3
+2

/home/sb/DataTest.php:11

FAILURES!
Tests: 4, Assertions: 4, Failures: 1.

例 4.6: CsvFileIterator クラス

<?php
class CsvFileIterator implements Iterator {
protected $file;
protected $key = 0;
protected $current;

public function __construct($file) {
$this->file = fopen($file, 'r');
}

public function __destruct() {
fclose($this->file);
}

public function rewind() {
rewind($this->file);
$this->current = fgetcsv($this->file);
$this->key = 0;
}

public function valid() {
return !feof($this->file);
}

public function key() {
return $this->key;
}

public function current() {
return $this->current;
}

public function next() {
$this->current = fgetcsv($this->file);
$this->key++;
}
}
?>

注記

@dataProvider で指定したメソッドと @depends で指定したテストの両方からの入力を受け取るテストの場合、 データプロバイダからの引数のほうが依存するテストからの引数より先にきます。

注記

あるテストがデータプロバイダを使う別のテストに依存している場合、 別のテストで少なくともひとつのデータセットに対するテストが成功すれば そのテストも実行されます。 データプロバイダを使ったテストの結果をそのテストに注入することはできません。

例外のテスト

例 4.7 は、テストするコード内で例外がスローされたかどうかを @expectedException アノテーションを使用して調べる方法を示すものです。

例 4.7: @expectedException アノテーションの使用法

<?php
class ExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testException()
{
}
}
?>
phpunit ExceptionTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.00Mb

There was 1 failure:

1) ExceptionTest::testException
Expected exception InvalidArgumentException


FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

さらに、@expectedExceptionMessage@expectedExceptionCode@expectedException と組み合わせて使うと、 例外メッセージや例外コードを 例 4.8 のようにテストできます。

例 4.8: @expectedExceptionMessage および @expectedExceptionCode アノテーションの使用法

<?php
class ExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Right Message
*/
public function testExceptionHasRightMessage()
{
throw new InvalidArgumentException('Some Message', 10);
}

/**
* @expectedException InvalidArgumentException
* @expectedExceptionCode 20
*/
public function testExceptionHasRightCode()
{
throw new InvalidArgumentException('Some Message', 10);
}
}
?>
phpunit ExceptionTest
PHPUnit 3.5.14 by Sebastian Bergmann.

FF

Time: 0 seconds, Memory: 5.50Mb

There were 2 failures:

1) ExceptionTest::testExceptionHasRightMessage
Failed asserting that <string:Some Message> contains "Right Message".


2) ExceptionTest::testExceptionHasRightCode
Failed asserting that <integer:10> matches expected <integer:20>.


FAILURES!
Tests: 2, Assertions: 2, Failures: 2.

一方、setExpectedException() メソッドを使用して、発生するであろう例外を指定することもできます。この方法を 例 4.9 に示します。

例 4.9: テスト対象のコードで発生するであろう例外の指定

<?php
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testException()
{
$this->setExpectedException('InvalidArgumentException');
}

public function testExceptionHasRightMessage()
{
$this->setExpectedException(
'InvalidArgumentException', 'Right Message'
);
throw new InvalidArgumentException('Some Message', 10);
}

public function testExceptionHasRightCode()
{
$this->setExpectedException(
'InvalidArgumentException', 'Right Message', 20
);
throw new InvalidArgumentException('The Right Message', 10);
}
}
?>
phpunit ExceptionTest
PHPUnit 3.5.14 by Sebastian Bergmann.

FFF

Time: 0 seconds, Memory: 5.50Mb

There were 3 failures:

1) ExceptionTest::testException
Expected exception InvalidArgumentException

/home/sb/ExceptionTest.php:6

2) ExceptionTest::testExceptionHasRightMessage
Failed asserting that <string:Some Message> contains "Right Message".


3) ExceptionTest::testExceptionHasRightCode
Failed asserting that <integer:10> matches expected <integer:20>.


FAILURES!
Tests: 3, Assertions: 4, Failures: 3.

表 4.1 は、例外をテストするために用意されているメソッドをまとめたものです。

表4.1 例外のテスト用のメソッド

メソッド 意味
void setExpectedException(string $exceptionName[, string $exceptionMessage = '', integer $exceptionCode = 0]) 期待する $exceptionName$exceptionMessage および $exceptionCode を設定します。
String getExpectedException() 発生することを期待する例外の名前を返します。

一方、 例 4.10 のような方法で例外をテストすることもできます。

例 4.10: 例外をテストするための、別の方法

<?php
class ExceptionTest extends PHPUnit_Framework_TestCase {
public function testException() {
try {
// ... 例外が発生するであろうコード ...
}

catch (InvalidArgumentException $expected) {
return;
}

$this->fail('期待通りの例外が発生しませんでした。');
}
}
?>

例外が発生するはずの 例 4.10 のコードで例外が発生しなかった場合、それに続く fail() によってテストが終了し、問題を報告します。期待通りに例外が発生すると、 catch ブロックが実行されてテストは正常終了します。

PHP のエラーのテスト

デフォルトでは、PHPUnit はテストの実行中に発生した PHP のエラーや警告そして notice を例外に変換します。これらの例外を用いて、たとえば 例 4.11 のように PHP のエラーが発生することをテストできます。

例 4.11: @expectedException を用いた、PHP エラーが発生することのテスト

<?php
class ExpectedErrorTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException PHPUnit_Framework_Error
*/
public function testFailingInclude()
{
include 'not_existing_file.php';
}
}
?>
phpunit ExpectedErrorTest
PHPUnit 3.5.14 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 5.00Mb

OK (1 test, 1 assertion)

PHPUnit_Framework_Error_Notice および PHPUnit_Framework_Error_Warning は、 それぞれ PHP の notice と警告に対応します。

注記

例外をテストするときには可能な限り限定的にしなければいけません。たとえば Exception クラスに対するテストは一般化されすぎており、 ほとんどの場合にあてはまってしまいます。また予期せぬ副作用を引き起こしかねません。

アサーション

この節では、利用可能なアサーションメソッドのの一覧を示します。

assertArrayHasKey()

assertArrayHasKey(mixed $key, array $array[, string $message = ''])

$array にキー $key が存在しない場合にエラー $message を報告します。

assertArrayNotHasKey() はこのアサーションの逆で、同じ引数をとります。

例 4.12: assertArrayHasKey() の使用法

<?php
class ArrayHasKeyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertArrayHasKey('foo', array('bar' => 'baz'));
}
}
?>
phpunit ArrayHasKeyTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertClassHasAttribute(string $attributeName, string $className[, string $message = ''])

$className::attributeName が存在しない場合にエラー $message を報告します。

assertClassNotHasAttribute() はこのアサーションの逆で、同じ引数をとります。

例 4.13: assertClassHasAttribute() の使用法

<?php
class ClassHasAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertClassHasAttribute('foo', 'stdClass');
}
}
?>
phpunit ClassHasAttributeTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertClassHasStaticAttribute(string $attributeName, string $className[, string $message = ''])

$className::attributeName が存在しない場合にエラー $message を報告します。

assertClassNotHasStaticAttribute() はこのアサーションの逆で、同じ引数をとります。

例 4.14: assertClassHasStaticAttribute() の使用法

<?php
class ClassHasStaticAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertClassHasStaticAttribute('foo', 'stdClass');
}
}
?>
phpunit ClassHasStaticAttributeTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertContains(mixed $needle, Iterator|array $haystack[, string $message = ''])

$needle$haystack の要素でない場合にエラー $message を報告します。

assertNotContains() はこのアサーションの逆で、同じ引数をとります。

assertAttributeContains()assertAttributeNotContains() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を haystack として使用することができます。

例 4.15: assertContains() の使用法

<?php
class ContainsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContains(4, array(1, 2, 3));
}
}
?>
phpunit ContainsTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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 を報告します。

例 4.16: assertContains() の使用法

<?php
class ContainsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContains('baz', 'foobar');
}
}
?>
phpunit ContainsTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertContainsOnly(string $type, Iterator|array $haystack[, boolean $isNativeType = NULL, string $message = ''])

$haystack の中身の型が $type だけではない場合にエラー $message を報告します。

$isNativeType はフラグで、$type がネイティブな PHP の型であるかどうかを表します。

assertNotContainsOnly() はこのアサーションの逆で、同じ引数をとります。

assertAttributeContainsOnly()assertAttributeNotContainsOnly() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を実際の値として使用することができます。

例 4.17: assertContainsOnly() の使用法

<?php
class ContainsOnlyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContainsOnly('string', array('1', '2', 3));
}
}
?>
phpunit ContainsOnlyTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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.

assertEmpty()

assertEmpty(mixed $actual[, string $message = ''])

$actual が空でない場合にエラー $message を報告します。

assertNotEmpty() はこのアサーションの逆で、同じ引数をとります。

assertAttributeEmpty() および assertAttributeNotEmpty() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性に対して使えます。

例 4.18: assertEmpty() の使用法

<?php
class EmptyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertEmpty(array('foo'));
}
}
?>
phpunit EmptyTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) EmptyTest::testFailure
Failed asserting that an array is empty.

/home/sb/EmptyTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

assertEqualXMLStructure()

assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement[, boolean $checkAttributes = FALSE, string $message = ''])

$actualElement の DOMElement の XML 構造が $expectedElement の DOMElement の XML 構造と等しくない場合にエラー $message を報告します。

例 4.19: assertEqualXMLStructure() の使用法

<?php
class EqualXMLStructureTest extends PHPUnit_Framework_TestCase
{
public function testFailureWithDifferentNodeNames()
{
$expected = new DOMElement('foo');
$actual = new DOMElement('bar');

$this->assertEqualXMLStructure($expected, $actual);
}

public function testFailureWithDifferentNodeAttributes()
{
$expected = new DOMDocument;
$expected->loadXML('<foo bar="true" />');

$actual = new DOMDocument;
$actual->loadXML('<foo/>');

$this->assertEqualXMLStructure(
$expected->firstChild, $actual->firstChild, TRUE
);
}

public function testFailureWithDifferentChildrenCount()
{
$expected = new DOMDocument;
$expected->loadXML('<foo><bar/><bar/><bar/></foo>');

$actual = new DOMDocument;
$actual->loadXML('<foo><bar/></foo>');

$this->assertEqualXMLStructure(
$expected->firstChild, $actual->firstChild
);
}

public function testFailureWithDifferentChildren()
{
$expected = new DOMDocument;
$expected->loadXML('<foo><bar/><bar/><bar/></foo>');

$actual = new DOMDocument;
$actual->loadXML('<foo><baz/><baz/><baz/></foo>');

$this->assertEqualXMLStructure(
$expected->firstChild, $actual->firstChild
);
}
}
?>
phpunit EqualXMLStructureTest
PHPUnit 3.5.14 by Sebastian Bergmann.

FFFF

Time: 0 seconds, Memory: 5.75Mb

There were 4 failures:

1) EqualXMLStructureTest::testFailureWithDifferentNodeNames
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-foo
+bar

/home/sb/EqualXMLStructureTest.php:9

2) EqualXMLStructureTest::testFailureWithDifferentNodeAttributes
Number of attributes on node "foo" does not match
Failed asserting that <integer:0> matches expected <integer:1>.

/home/sb/EqualXMLStructureTest.php:22

3) EqualXMLStructureTest::testFailureWithDifferentChildrenCount
Number of child nodes of "foo" differs
Failed asserting that <integer:1> matches expected <integer:3>.

/home/sb/EqualXMLStructureTest.php:35

4) EqualXMLStructureTest::testFailureWithDifferentChildren
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-bar
+baz

/home/sb/EqualXMLStructureTest.php:48

FAILURES!
Tests: 4, Assertions: 8, Failures: 4.

assertEquals()

assertEquals(mixed $expected, mixed $actual[, string $message = ''])

2 つの変数 $expected$actual が等しくない場合にエラー $message を報告します。

assertNotEquals() はこのアサーションの逆で、同じ引数をとります。

assertAttributeEquals()assertAttributeNotEquals() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を実際の値として使用することができます。

例 4.20: 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.5.14 by Sebastian Bergmann.

FFF

Time: 0 seconds, Memory: 5.50Mb

There were 3 failures:

1) EqualsTest::testFailure
Failed asserting that <integer:0> matches expected <integer:1>.

/home/sb/EqualsTest.php:6

2) EqualsTest::testFailure2
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-bar
+baz

/home/sb/EqualsTest.php:11

3) EqualsTest::testFailure3
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
 foo
-bar
+bah
 baz

/home/sb/EqualsTest.php:16

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 を参照ください。

例 4.21: 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.5.14 by Sebastian Bergmann.

.F

Time: 0 seconds, Memory: 5.50Mb

There was 1 failure:

1) EqualsTest::testFailure
Failed asserting that <double:1.1> matches expected <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 を報告します。

例 4.22: 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.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) EqualsTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
 <?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 を報告します。

例 4.23: オブジェクトでの 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.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.50Mb

There was 1 failure:

1) EqualsTest::testFailure
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
 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 を報告します。

例 4.24: 配列での 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.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.50Mb

There was 1 failure:

1) EqualsTest::testFailure
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
 Array
 (
     [0] => a
-    [1] => b
-    [2] => c
+    [1] => c
+    [2] => d
 )

/home/sb/EqualsTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

assertFalse()

assertFalse(bool $condition[, string $message = ''])

$conditionTRUE の場合にエラー $message を報告します。

例 4.25: assertFalse() の使用法

<?php
class FalseTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFalse(TRUE);
}
}
?>
phpunit FalseTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) FalseTest::testFailure
Failed asserting that <boolean:true> is false.

/home/sb/FalseTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

assertFileEquals()

assertFileEquals(string $expected, string $actual[, string $message = ''])

$expected で指定したファイルと $actual で指定したファイルの内容が異なる場合にエラー $message を報告します。

assertFileNotEquals() はこのアサーションの逆で、同じ引数をとります。

例 4.26: assertFileEquals() の使用法

<?php
class FileEqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFileEquals('/home/sb/expected', '/home/sb/actual');
}
}
?>
phpunit FileEqualsTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.50Mb

There was 1 failure:

1) FileEqualsTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-expected
+actual

/home/sb/FileEqualsTest.php:6

FAILURES!
Tests: 1, Assertions: 3, Failures: 1.

assertFileExists()

assertFileExists(string $filename[, string $message = ''])

ファイル $filename が存在しない場合にエラー $message を報告します。

assertFileNotExists() はこのアサーションの逆で、同じ引数をとります。

例 4.27: assertFileExists() の使用法

<?php
class FileExistsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFileExists('/path/to/file');
}
}
?>
phpunit FileExistsTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertGreaterThan(mixed $expected, mixed $actual[, string $message = ''])

$actual の値が $expected の値より大きくない場合にエラー $message を報告します。

assertAttributeGreaterThan() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を実際の値として使用することができます。

例 4.28: assertGreaterThan() の使用法

<?php
class GreaterThanTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertGreaterThan(2, 1);
}
}
?>
phpunit GreaterThanTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertGreaterThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])

$actual の値が $expected の値以上でない場合にエラー $message を報告します。

assertAttributeGreaterThanOrEqual() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を実際の値として使用することができます。

例 4.29: assertGreaterThanOrEqual() の使用法

<?php
class GreatThanOrEqualTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertGreaterThanOrEqual(2, 1);
}
}
?>
phpunit GreaterThanOrEqualTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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: 2, Failures: 1.

assertInstanceOf()

assertInstanceOf($expected, $actual[, $message = ''])

$actual$expected のインスタンスでない場合にエラー $message を報告します。

assertNotInstanceOf() はこのアサーションの逆で、同じ引数をとります。

assertAttributeInstanceOf() および assertAttributeNotInstanceOf() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性に対して使えます。

例 4.30: assertInstanceOf() の使用法

<?php
class InstanceOfTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertInstanceOf('RuntimeException', new Exception);
}
}
?>
phpunit InstanceOfTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) InstanceOfTest::testFailure
Failed asserting that <Exception> is an instance of class "RuntimeException".

/home/sb/InstanceOfTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

assertInternalType()

assertInternalType($expected, $actual[, $message = ''])

$actual の型が $expected でない場合にエラー $message を報告します。

assertNotInternalType() はこのアサーションの逆で、同じ引数をとります。

assertAttributeInternalType() および assertAttributeNotInternalType() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性に対して使えます。

例 4.31: assertInternalType() の使用法

<?php
class InternalTypeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertInternalType('string', 42);
}
}
?>
phpunit InternalTypeTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) InternalTypeTest::testFailure
Failed asserting that <integer:42> is of type "string".

/home/sb/InternalTypeTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

assertLessThan()

assertLessThan(mixed $expected, mixed $actual[, string $message = ''])

$actual の値が $expected の値より小さくない場合にエラー $message を報告します。

assertAttributeLessThan() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を実際の値として使用することができます。

例 4.32: assertLessThan() の使用法

<?php
class LessThanTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertLessThan(1, 2);
}
}
?>
phpunit LessThanTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertLessThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])

$actual の値が $expected の値以下でない場合にエラー $message を報告します。

assertAttributeLessThanOrEqual() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を実際の値として使用することができます。

例 4.33: assertLessThanOrEqual() の使用法

<?php
class LessThanOrEqualTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertLessThanOrEqual(1, 2);
}
}
?>
phpunit LessThanOrEqualTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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: 2, Failures: 1.

assertNull()

assertNull(mixed $variable[, string $message = ''])

$variableNULL でないときにエラー $message を報告します。

assertNotNull() はこのアサーションの逆で、同じ引数をとります。

例 4.34: assertNull() の使用法

<?php
class NullTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertNull('foo');
}
}
?>
phpunit NotNullTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) NullTest::testFailure
Failed asserting that <string:foo> is null.

/home/sb/NotNullTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

assertObjectHasAttribute()

assertObjectHasAttribute(string $attributeName, object $object[, string $message = ''])

$object->attributeName が存在しない場合にエラー $message を報告します。

assertObjectNotHasAttribute() はこのアサーションの逆で、同じ引数をとります。

例 4.35: assertObjectHasAttribute() の使用法

<?php
class ObjectHasAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertObjectHasAttribute('foo', new stdClass);
}
}
?>
phpunit ObjectHasAttributeTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertRegExp(string $pattern, string $string[, string $message = ''])

$string が正規表現 $pattern にマッチしない場合にエラー $message を報告します。

assertNotRegExp() はこのアサーションの逆で、同じ引数をとります。

例 4.36: assertRegExp() の使用法

<?php
class RegExpTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertRegExp('/foo/', 'bar');
}
}
?>
phpunit RegExpTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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.

assertStringMatchesFormat()

assertStringMatchesFormat(string $format, string $string[, string $message = ''])

$string が書式文字列 $format にマッチしない場合にエラー $message を報告します。

assertStringNotMatchesFormat() はこのアサーションの逆で、同じ引数をとります。

例 4.37: assertStringMatchesFormat() の使用法

<?php
class StringMatchesFormatTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringMatchesFormat('%i', 'foo');
}
}
?>
phpunit StringMatchesFormatTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) StringMatchesFormatTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-%i
+foo

/home/sb/StringMatchesFormatTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

書式文字列には次のプレースホルダを含めることができます。

  • %e: ディレクトリ区切り文字、たとえば Linux なら / を表します。

  • %s: 一文字以上の何か (文字あるいは空白)、ただし改行文字は含みません。

  • %S: ゼロ文字以上の何か (文字あるいは空白)、ただし改行文字は含みません。

  • %a: 一文字以上の何か (文字あるいは空白)、改行文字も含みます。

  • %A: ゼロ文字以上の何か (文字あるいは空白)、改行文字も含みます。

  • %w: ゼロ文字以上の空白。

  • %i: 符号付き整数値。例: +3142, -3142

  • %d: 符号なし整数値。例: 123456

  • %x: 一文字以上の十六進文字 (0-9, a-f, A-F)。

  • %f: 浮動小数点数値。例: 3.142, -3.142, 3.142E-10, 3.142e+10

  • %c: 任意の一文字。

assertStringMatchesFormatFile()

assertStringMatchesFormatFile(string $formatFile, string $string[, string $message = ''])

$string$formatFile の内容にマッチしない場合にエラー $message を報告します。

assertStringNotMatchesFormatFile() はこのアサーションの逆で、同じ引数をとります。

例 4.38: assertStringMatchesFormatFile() の使用法

<?php
class StringMatchesFormatFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringMatchesFormatFile('/path/to/expected.txt', 'foo');
}
}
?>
phpunit StringMatchesFormatFileTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) StringMatchesFormatFileTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-%i
-
+foo

/home/sb/StringMatchesFormatFileTest.php:6

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.

assertSame()

assertSame(mixed $expected, mixed $actual[, string $message = ''])

2 つの変数 $expected$actual が同じ型・同じ値でない場合にエラー $message を報告します。

assertNotSame() はこのアサーションの逆で、同じ引数をとります。

assertAttributeSame()assertAttributeNotSame() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を実際の値として使用することができます。

例 4.39: assertSame() の使用法

<?php
class SameTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertSame('2204', 2204);
}
}
?>
phpunit SameTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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 を報告します。

例 4.40: オブジェクトでの assertSame() の使用法

<?php
class SameTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertSame(new stdClass, new stdClass);
}
}
?>
phpunit SameTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertSelectCount(array $selector, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])

CSS セレクタ $selector が DOMNode $actual$count 要素にマッチしない場合にエラー $message を報告します。

$count には次の型のいずれかを指定できます。

  • boolean: セレクタにマッチする要素が存在する (TRUE) か存在しない (FALSE) かを調べます。
  • integer: 要素の数を調べます。
  • array: 要素の数が指定した範囲にあるかどうかを調べます。<, >, <=, および >= をキーとして範囲を指定します。

例 4.41: assertSelectCount() の使用法

<?php
class SelectCountTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
$this->xml = new DomDocument;
$this->xml->loadXML('<foo><bar/><bar/><bar/></foo>');
}

public function testAbsenceFailure()
{
$this->assertSelectCount('foo bar', FALSE, $this->xml);
}

public function testPresenceFailure()
{
$this->assertSelectCount('foo baz', TRUE, $this->xml);
}

public function testExactCountFailure()
{
$this->assertSelectCount('foo bar', 5, $this->xml);
}

public function testRangeFailure()
{
$this->assertSelectCount('foo bar', array('>'=>6, '<'=>8), $this->xml);
}
}
?>
phpunit SelectCountTest
PHPUnit 3.5.14 by Sebastian Bergmann.

FFFF

Time: 0 seconds, Memory: 5.75Mb

There were 4 failures:

1) SelectCountTest::testAbsenceFailure
Failed asserting that <boolean:true> is false.

/home/sb/SelectCountTest.php:12

2) SelectCountTest::testPresenceFailure
Failed asserting that <boolean:false> is true.

/home/sb/SelectCountTest.php:17

3) SelectCountTest::testExactCountFailure
Failed asserting that <integer:3> matches expected <integer:5>.

/home/sb/SelectCountTest.php:22

4) SelectCountTest::testRangeFailure
Failed asserting that <boolean:false> is true.

/home/sb/SelectCountTest.php:27

FAILURES!
Tests: 4, Assertions: 4, Failures: 4.

assertSelectEquals()

assertSelectEquals(array $selector, string $content, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])

CSS セレクタ $selector が DOMNode $actual の値 $content$count 要素にマッチしない場合にエラー $message を報告します。

$count には次の型のいずれかを指定できます。

  • boolean: セレクタにマッチする要素が存在する (TRUE) か存在しない (FALSE) かを調べます。
  • integer: 要素の数を調べます。
  • array: 要素の数が指定した範囲にあるかどうかを調べます。<, >, <=, および >= をキーとして範囲を指定します。

例 4.42: assertSelectEquals() の使用法

<?php
class SelectEqualsTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
$this->xml = new DomDocument;
$this->xml->loadXML('<foo><bar>Baz</bar><bar>Baz</bar></foo>');
}

public function testAbsenceFailure()
{
$this->assertSelectEquals('foo bar', 'Baz', FALSE, $this->xml);
}

public function testPresenceFailure()
{
$this->assertSelectEquals('foo bar', 'Bat', TRUE, $this->xml);
}

public function testExactCountFailure()
{
$this->assertSelectEquals('foo bar', 'Baz', 5, $this->xml);
}

public function testRangeFailure()
{
$this->assertSelectEquals('foo bar', 'Baz', array('>'=>6, '<'=>8), $this->xml);
}
}
?>
phpunit SelectEqualsTest
PHPUnit 3.5.14 by Sebastian Bergmann.

FFFF

Time: 0 seconds, Memory: 5.75Mb

There were 4 failures:

1) SelectEqualsTest::testAbsenceFailure
Failed asserting that <boolean:true> is false.

/home/sb/SelectEqualsTest.php:12

2) SelectEqualsTest::testPresenceFailure
Failed asserting that <boolean:false> is true.

/home/sb/SelectEqualsTest.php:17

3) SelectEqualsTest::testExactCountFailure
Failed asserting that <integer:2> matches expected <integer:5>.

/home/sb/SelectEqualsTest.php:22

4) SelectEqualsTest::testRangeFailure
Failed asserting that <boolean:false> is true.

/home/sb/SelectEqualsTest.php:27

FAILURES!
Tests: 4, Assertions: 4, Failures: 4.

assertSelectRegExp()

assertSelectRegExp(array $selector, string $pattern, integer $count, mixed $actual[, string $message = '', boolean $isHtml = TRUE])

CSS セレクタ $selector が DOMNode $actual のパターン $pattern にマッチする値の $count 要素にマッチしない場合にエラー $message を報告します。

$count には次の型のいずれかを指定できます。

  • boolean: セレクタにマッチする要素が存在する (TRUE) か存在しない (FALSE) かを調べます。
  • integer: 要素の数を調べます。
  • array: 要素の数が指定した範囲にあるかどうかを調べます。<, >, <=, および >= をキーとして範囲を指定します。

例 4.43: assertSelectRegExp() の使用法

<?php
class SelectRegExpTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
$this->xml = new DomDocument;
$this->xml->loadXML('<foo><bar>Baz</bar><bar>Baz</bar></foo>');
}

public function testAbsenceFailure()
{
$this->assertSelectRegExp('foo bar', '/Ba.*/', FALSE, $this->xml);
}

public function testPresenceFailure()
{
$this->assertSelectRegExp('foo bar', '/B[oe]z]/', TRUE, $this->xml);
}

public function testExactCountFailure()
{
$this->assertSelectRegExp('foo bar', '/Ba.*/', 5, $this->xml);
}

public function testRangeFailure()
{
$this->assertSelectRegExp('foo bar', '/Ba.*/', array('>'=>6, '<'=>8), $this->xml);
}
}
?>
phpunit SelectRegExpTest
PHPUnit 3.5.14 by Sebastian Bergmann.

FFFF

Time: 0 seconds, Memory: 5.75Mb

There were 4 failures:

1) SelectRegExpTest::testAbsenceFailure
Failed asserting that <boolean:true> is false.

/home/sb/SelectRegExpTest.php:12

2) SelectRegExpTest::testPresenceFailure
Failed asserting that <boolean:false> is true.

/home/sb/SelectRegExpTest.php:17

3) SelectRegExpTest::testExactCountFailure
Failed asserting that <integer:2> matches expected <integer:5>.

/home/sb/SelectRegExpTest.php:22

4) SelectRegExpTest::testRangeFailure
Failed asserting that <boolean:false> is true.

/home/sb/SelectRegExpTest.php:27

FAILURES!
Tests: 4, Assertions: 4, Failures: 4.

assertStringEndsWith()

assertStringEndsWith(string $suffix, string $string[, string $message = ''])

$string$suffix で終わっていない場合にエラー $message を報告します。

assertStringEndsNotWith() はこのアサーションの逆で、同じ引数をとります。

例 4.44: assertStringEndsWith() の使用法

<?php
class StringEndsWithTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringEndsWith('suffix', 'foo');
}
}
?>
phpunit StringEndsWithTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

assertStringEqualsFile(string $expectedFile, string $actualString[, string $message = ''])

$expectedFile で指定したファイルの内容に $actualString が含まれない場合にエラー $message を報告します。

assertStringNotEqualsFile() はこのアサーションの逆で、同じ引数をとります。

例 4.45: assertStringEqualsFile() の使用法

<?php
class StringEqualsFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringEqualsFile('/home/sb/expected', 'actual');
}
}
?>
phpunit StringEqualsFileTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 1 second, Memory: 5.50Mb

There was 1 failure:

1) StringEqualsFileTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-expected
-
+actual

/home/sb/StringEqualsFileTest.php:6

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.

assertStringStartsWith()

assertStringStartsWith(string $prefix, string $string[, string $message = ''])

$string$prefix で始まっていない場合にエラー $message を報告します。

assertStringStartsNotWith() はこのアサーションの逆で、同じ引数をとります。

例 4.46: assertStringStartsWith() の使用法

<?php
class StringStartsWithTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringStartsWith('prefix', 'foo');
}
}
?>
phpunit StringStartsWithTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

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()

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() はこのアサーションの逆で、同じ引数をとります。

例 4.47: 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);
?>

assertThat()

もっと複雑なアサーションを行う場合には、 PHPUnit_Framework_Constraint クラスを使用します。 これらは、assertThat() メソッドを使用して評価されます。 例 4.48 は、 logicalNot()equalTo() を用いて assertNotEquals() と同じアサーションを行う方法を示すものです。

assertThat(mixed $value, PHPUnit_Framework_Constraint $constraint[, $message = ''])

$value$constraint にマッチしない場合にエラー $message を報告します。

例 4.48: 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)
)
);
}
}
?>

表 4.2 に、 使用できる PHPUnit_Framework_Constraint クラスをまとめます。

表4.2 制約

制約 意味
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()

assertTrue(bool $condition[, string $message = ''])

$conditionFALSE の場合にエラー $message を報告します。

例 4.49: assertTrue() の使用法

<?php
class TrueTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertTrue(FALSE);
}
}
?>
phpunit TrueTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) TrueTest::testFailure
Failed asserting that <boolean:false> is true.

/home/sb/TrueTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

assertType()

assertType(string $expected, mixed $actual[, string $message = ''])

変数 $actual の型が $expected でない場合にエラー $message を報告します。

assertNotType() はこのアサーションの逆で、同じ引数をとります。

assertAttributeType()assertAttributeNotType() は便利なラッパーで、クラスやオブジェクトの publicprotectedprivate 属性を実際の値として使用することができます。

例 4.50: assertType() の使用法

<?php
class TypeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertType('Exception', new stdClass);
}
}
?>
phpunit TypeTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) TypeTest::testFailure
Failed asserting that <stdClass> is an instance of class "Exception".

/home/sb/TypeTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Warning: Deprecated PHPUnit features are being used 1 times!
Use --verbose for more information.

一方、$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")

例 4.51: assertType() の使用法

<?php
class TypeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertType(PHPUnit_Framework_Constraint_IsType::TYPE_STRING, 2204);
}
}
?>
phpunit TypeTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) TypeTest::testFailure
Failed asserting that <integer:2204> is of type "string".

/home/sb/TypeTest.php:6

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Warning: Deprecated PHPUnit features are being used 1 times!
Use --verbose for more information.

注記

assertType() は PHPUnit 3.6 で削除されるので、使ってはいけません。integerstring といった内部的な型を確かめるには assertInternalType (assertInternalType() を参照ください)、そしてオブジェクトが指定したクラスやインターフェイスのインスタンスであることを確かめるには assertInstanceOf (assertInstanceOf() を参照ください) をそれぞれ使いましょう。

assertXmlFileEqualsXmlFile()

assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile[, string $message = ''])

$actualFile の XML ドキュメントが $expectedFile の XML ドキュメントと異なる場合にエラー $message を報告します。

assertXmlFileNotEqualsXmlFile() はこのアサーションの逆で、同じ引数をとります。

例 4.52: 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.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.50Mb

There was 1 failure:

1) XmlFileEqualsXmlFileTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
 <?xml version="1.0"?>
 <foo>
-  <bar/>
+  <baz/>
 </foo>

/home/sb/XmlFileEqualsXmlFileTest.php:7

FAILURES!
Tests: 1, Assertions: 3, Failures: 1.

assertXmlStringEqualsXmlFile()

assertXmlStringEqualsXmlFile(string $expectedFile, string $actualXml[, string $message = ''])

$actualXml の XML ドキュメントが $expectedFile の XML ドキュメントと異なる場合にエラー $message を報告します。

assertXmlStringNotEqualsXmlFile() はこのアサーションの逆で、同じ引数をとります。

例 4.53: assertXmlStringEqualsXmlFile() の使用法

<?php
class XmlStringEqualsXmlFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlStringEqualsXmlFile(
'/home/sb/expected.xml', '<foo><baz/></foo>');
}
}
?>
phpunit XmlStringEqualsXmlFileTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.50Mb

There was 1 failure:

1) XmlStringEqualsXmlFileTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
 <?xml version="1.0"?>
 <foo>
-  <bar/>
+  <baz/>
 </foo>

/home/sb/XmlStringEqualsXmlFileTest.php:7

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.

assertXmlStringEqualsXmlString()

assertXmlStringEqualsXmlString(string $expectedXml, string $actualXml[, string $message = ''])

$actualXml の XML ドキュメントが $expectedXml の XML ドキュメントと異なる場合にエラー $message を報告します。

assertXmlStringNotEqualsXmlString() はこのアサーションの逆で、同じ引数をとります。

例 4.54: assertXmlStringEqualsXmlString() の使用法

<?php
class XmlStringEqualsXmlStringTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlStringEqualsXmlString(
'<foo><bar/></foo>', '<foo><baz/></foo>');
}
}
?>
phpunit XmlStringEqualsXmlStringTest
PHPUnit 3.5.14 by Sebastian Bergmann.

F

Time: 0 seconds, Memory: 5.25Mb

There was 1 failure:

1) XmlStringEqualsXmlStringTest::testFailure
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
 <?xml version="1.0"?>
 <foo>
-  <bar/>
+  <baz/>
 </foo>

/home/sb/XmlStringEqualsXmlStringTest.php:7

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Prev Next
1. 自動テスト
2. PHPUnit の目標
3. PHPUnit のインストール
4. PHPUnit 用のテストの書き方
テストの依存性
データプロバイダ
例外のテスト
PHP のエラーのテスト
アサーション
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertEmpty()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertInstanceOf()
assertInternalType()
assertLessThan()
assertLessThanOrEqual()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMatchesFormat()
assertStringMatchesFormatFile()
assertSame()
assertSelectCount()
assertSelectEquals()
assertSelectRegExp()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertTag()
assertThat()
assertTrue()
assertType()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
5. コマンドラインのテストランナー
6. Fixtures
tearDown() よりも setUp()
バリエーション
Fixture の共有
グローバルな状態
7. テストの構成
ファイルシステムを用いたテストスイートの構成
XML 設定ファイルを用いたテストスイートの構成
8. テストケースの拡張
出力内容のテスト
9. データベースのテスト
データベースのテストに対応しているベンダー
データベースのテストの難しさ
データベーステストの四段階
1. データベースのクリーンアップ
2. フィクスチャの準備
3–5. テストの実行、結果の検証、そして後始末
PHPUnit のデータベーステストケースの設定
getConnection() の実装
getDataSet() の実装
データベーススキーマ (DDL) とは?
ヒント: 自前でのデータベーステストケースの抽象化
データセットとデータテーブルについて知る
利用できる実装
外部キーには注意
自作のデータセットやデータテーブルの実装
接続 API
データベースアサーション API
テーブルの行数のアサーション
テーブルの状態のアサーション
クエリの結果のアサーション
複数のテーブルの状態のアサーション
よくある質問
PHPUnit は、テストごとにデータベーススキーマを作り直すの?
PDO を使ったアプリケーションじゃないと Database Extension を使えないの?
Too much Connections というエラーが出たらどうすればいい?
フラット XML や CSV のデータセットで NULL を扱う方法は?
10. 不完全なテスト・テストの省略
不完全なテスト
テストの省略
11. テストダブル
スタブ
モックオブジェクト
ウェブサービスのスタブおよびモック
ファイルシステムのモック
12. テストの進め方
開発中のテスト
デバッグ中のテスト
13. テスト駆動開発
銀行口座の例
14. 振舞駆動開発
ボウリングゲームの例
15. コードカバレッジ解析
カバーするメソッドの指定
コードブロックの無視
ファイルのインクルードや除外
16. テストのその他の使用法
アジャイルな文書作成
複数チームでのテスト
17. 雛形ジェネレータ
テストケースクラスの雛形の作成
テストケースクラスからのクラスの雛形の作成
18. PHPUnit と Selenium
Selenium RC
PHPUnit_Extensions_SeleniumTestCase
19. ログ出力
テスト結果 (XML)
テスト結果 (TAP)
テスト結果 (JSON)
コードカバレッジ (XML)
20. PHPUnit の拡張
PHPUnit_Framework_TestCase のサブクラスの作成
カスタムアサーションの作成
PHPUnit_Framework_TestListener の実装
PHPUnit_Extensions_TestDecorator のサブクラスの作成
PHPUnit_Framework_Test の実装
A. アサーション
B. アノテーション
@assert
@author
@backupGlobals
@backupStaticAttributes
@covers
@dataProvider
@depends
@expectedException
@expectedExceptionCode
@expectedExceptionMessage
@group
@outputBuffering
@runTestsInSeparateProcesses
@runInSeparateProcess
@test
@testdox
@ticket
C. XML 設定ファイル
PHPUnit
テストスイート
グループ
コードカバレッジ対象のファイルの追加や除外
ログ出力
テストリスナー
PHP INI 項目や定数、グローバル変数の設定
Selenium RC の設定ブラウザ
D. 目次
E. 参考文献
F. 著作権