例 4.1展示了如何用 PHPUnit 编写测试来对 PHP 数组操作进行测试。本例介绍了用 PHPUnit 编写测试的基本惯例与步骤:
-
针对类
Class
的测试写在类ClassTest
中。 -
ClassTest
(通常)继承自PHPUnit_Framework_TestCase
。 -
测试都是命名为
test*
的公用方法。 -
在测试方法内,类似于
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));
}
}
?>
当你想把一些东西写到 | ||
--Martin Fowler |
单元测试主要是作为一种良好实践来编写的,它能帮助开发人员识别并修复 bug、重构代码,还可以看作被测软件单元的文档。要实现这些好处,理想的单元测试应当覆盖程序中所有可能的路径。一个单元测试通常覆盖一个函数或方法中的一个特定路径。但是,测试方法并不一定非要是一个封装良好的独立实体。测试方法之间经常有隐含的依赖关系暗藏在测试的实现方案中。 | ||
--Adrian Kuhn et. al. |
PHPUnit支持对测试方法之间的显式依赖关系进行声明。这种依赖关系并不是定义在测试方法的执行顺序中,而是允许生产者(producer)返回一个测试基境(fixture)的实例,并将此实例传递给依赖于它的消费者(consumer)们。
-
生产者(producer),是能生成被测单元并将其作为返回值的测试方法。
-
消费者(consumer),是依赖于一个或多个生产者及其返回值的测试方法。
例 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.8.0 by Sebastian Bergmann.
FS
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) DependencyFailureTest::testOne
Failed asserting that 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 不会更改测试的运行顺序,因此你需要自行保证某个测试所依赖的所有测试均出现于这个测试之前。
拥有多个 @depends
标注的测试,其第一个参数是第一个生产者提供的基境,第二个参数是第二个生产者提供的基境,以此类推。参见例 4.4。
例 4.4: 有多重依赖的测试
<?php
class MultipleDependenciesTest extends PHPUnit_Framework_TestCase
{
public function testProducerFirst()
{
$this->assertTrue(true);
return 'first';
}
public function testProducerSecond()
{
$this->assertTrue(true);
return 'second';
}
/**
* @depends testProducerFirst
* @depends testProducerSecond
*/
public function testConsumer()
{
$this->assertEquals(
array('first', 'second'),
func_get_args()
);
}
}
?>
phpunit --verbose MultipleDependenciesTest
PHPUnit 3.7.0 by Sebastian Bergmann.
...
Time: 0 seconds, Memory: 3.25Mb
OK (3 tests, 3 assertions)
测试方法可以接受任意参数。这些参数由数据供给器方法(在例 4.5中,是 provider()
方法)提供。用 @dataProvider
标注来指定使用哪个数据供给器方法。
数据供给器方法必须声明为 public
,其返回值要么是一个数组,其每个元素也是数组;要么是一个实现了 Iterator
接口的对象,在对它进行迭代时每步产生一个数组。每个数组都是测试数据集的一部分,将以它的内容作为参数来调用测试方法。
例 4.5: 使用返回数组的数组的数据供给器
<?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.8.0 by Sebastian Bergmann.
...F
Time: 0 seconds, Memory: 5.75Mb
There was 1 failure:
1) DataTest::testAdd with data set #3 (1, 1, 3)
Failed asserting that 2 matches expected 3.
/home/sb/DataTest.php:9
FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
例 4.6: 使用返回迭代器对象的数据供给器
<?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.8.0 by Sebastian Bergmann.
...F
Time: 0 seconds, Memory: 5.75Mb
There was 1 failure:
1) DataTest::testAdd with data set #3 ('1', '1', '3')
Failed asserting that 2 matches expected '3'.
/home/sb/DataTest.php:11
FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
例 4.7: 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.8
例 4.8: 在同一个测试中组合使用 @depends 和 @dataProvider
<?php
class DependencyAndDataProviderComboTest extends PHPUnit_Framework_TestCase
{
public function provider()
{
return array(array('provider1'), array('provider2'));
}
public function testProducerFirst()
{
$this->assertTrue(true);
return 'first';
}
public function testProducerSecond()
{
$this->assertTrue(true);
return 'second';
}
/**
* @depends testProducerFirst
* @depends testProducerSecond
* @dataProvider provider
*/
public function testConsumer()
{
$this->assertEquals(
array('provider1', 'first', 'second'),
func_get_args()
);
}
}
?>
phpunit --verbose DependencyAndDataProviderComboTest
PHPUnit 3.7.0 by Sebastian Bergmann.
...F
Time: 0 seconds, Memory: 3.50Mb
There was 1 failure:
1) DependencyAndDataProviderComboTest::testConsumer with data set #1 ('provider2')
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 0 => 'provider1'
+ 0 => 'provider2'
1 => 'first'
2 => 'second'
)
/home/sb/DependencyAndDataProviderComboTest.php:31
FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
例 4.9展示了如何用 @expectedException
标注来测试被测代码中是否抛出了异常。
例 4.9: 使用 @expectedException 标注
<?php
class ExceptionTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testException()
{
}
}
?>
phpunit ExceptionTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 4.75Mb
There was 1 failure:
1) ExceptionTest::testException
Expected exception InvalidArgumentException
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
另外,你可以将 @expectedExceptionMessage
和 @expectedExceptionCode
与 @expectedException
联合使用,来对异常的讯息与代号进行测试,如例 4.10所示。
例 4.10: 使用 @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.8.0 by Sebastian Bergmann.
FF
Time: 0 seconds, Memory: 3.00Mb
There were 2 failures:
1) ExceptionTest::testExceptionHasRightMessage
Failed asserting that exception message 'Some Message' contains 'Right Message'.
2) ExceptionTest::testExceptionHasRightCode
Failed asserting that expected exception code 20 is equal to 10.
FAILURES!
Tests: 2, Assertions: 4, Failures: 2.
关于 @expectedExceptionMessage
和 @expectedExceptionCode
,分别在“@expectedExceptionMessage”一节和“@expectedExceptionCode”一节有更多相关范例。
此外,还可以用 setExpectedException()
方法来设定所预期的异常,如例 4.11所示。
例 4.11: 预期被测代码将引发异常
<?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.8.0 by Sebastian Bergmann.
FFF
Time: 0 seconds, Memory: 3.00Mb
There were 3 failures:
1) ExceptionTest::testException
Expected exception InvalidArgumentException
2) ExceptionTest::testExceptionHasRightMessage
Failed asserting that exception message 'Some Message' contains 'Right Message'.
3) ExceptionTest::testExceptionHasRightCode
Failed asserting that expected exception code 20 is equal to 10.
FAILURES!
Tests: 3, Assertions: 6, Failures: 3.
表 4.1中列举了用于对异常进行测试的各种方法。
表 4.1. 用于对异常进行测试的方法
方法 | 含义 |
---|---|
void setExpectedException(string $exceptionName[, string $exceptionMessage = '', integer $exceptionCode = NULL]) | 设定预期的$exceptionName ,$exceptionMessage ,和 $exceptionCode 。 |
String getExpectedException() | 返回预期异常的名称。 |
你可以用例 4.12中所示方法来对异常进行测试。
例 4.12: 另一种对异常进行测试的方法
<?php
class ExceptionTest extends PHPUnit_Framework_TestCase {
public function testException() {
try {
// ... 预期会引发异常的代码 ...
}
catch (InvalidArgumentException $expected) {
return;
}
$this->fail('预期的异常未出现。');
}
}
?>
当例 4.12中预期会引发异常的代码并没有引发异常时,后面对 fail()
的调用将会中止测试,并通告测试有问题。如果预期的异常出现了,将执行 catch
代码块,测试将会成功结束。
默认情况下,PHPUnit 将测试在执行中触发的 PHP 错误、警告、通知都转换为异常。利用这些异常,就可以,比如说,预期测试将触发 PHP 错误,如例 4.13所示。
注意
PHP 的 error_reporting
运行时配置会对 PHPUnit 将哪些错误转换为异常有所限制。如果在这个特性上碰到问题,请确认 PHP 的配置中没有抑制想要测试的错误类型。
例 4.13: 用 @expectedException 来预期 PHP 错误
<?php
class ExpectedErrorTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException PHPUnit_Framework_Error
*/
public function testFailingInclude()
{
include 'not_existing_file.php';
}
}
?>
phpunit -d error_reporting=2 ExpectedErrorTest
PHPUnit 3.8.0 by Sebastian Bergmann.
.
Time: 0 seconds, Memory: 5.25Mb
OK (1 test, 1 assertion)
PHPUnit_Framework_Error_Notice
和 PHPUnit_Framework_Error_Warning
分别代表 PHP 通知与 PHP 警告。
注意
对异常进行测试是越明确越好的。对太笼统的类进行测试有可能导致不良副作用。因此,不再允许用@expectedException
或 setExpectedException()
对 Exception
类进行测试。
如果测试依靠会触发错误的 PHP 函数,例如 fopen
,有时候在测试中使用错误抑制符会很有用。通过抑制住错误通知,就能对返回值进行检查,否则错误通知将会导致抛出PHPUnit_Framework_Error_Notice
。
例 4.14: 对会引发PHP 错误的代码的返回值进行测试
<?php
class ErrorSuppressionTest extends PHPUnit_Framework_TestCase
{
public function testFileWriting() {
$writer = new FileWriter;
$this->assertFalse(@$writer->write('/is-not-writeable/file', 'stuff'));
}
}
class FileWriter
{
public function write($file, $content) {
$file = fopen($file, 'w');
if($file == false) {
return false;
}
// ...
}
}
?>
phpunit ErrorSuppressionTest
PHPUnit 3.8.0 by Sebastian Bergmann.
.
Time: 1 seconds, Memory: 5.25Mb
OK (1 test, 1 assertion)
如果不使用错误抑制符,此测试将会失败,并报告fopen(/is-not-writeable/file): failed to open stream: No such file or directory
。
有时候,想要断言,比如说,生成了预期的输出(例如,通过 echo
或 print
)。PHPUnit_Framework_TestCase
类使用 PHP 的 输出缓冲 特性来为此提供必要的功能。
例 4.15展示了如何用 expectOutputString()
方法来设定所预期的输出。如果没有产生预期的输出,测试将计为失败。
例 4.15: 对函数或方法的输出进行测试
<?php
class OutputTest extends PHPUnit_Framework_TestCase
{
public function testExpectFooActualFoo()
{
$this->expectOutputString('foo');
print 'foo';
}
public function testExpectBarActualBaz()
{
$this->expectOutputString('bar');
print 'baz';
}
}
?>
phpunit OutputTest
PHPUnit 3.8.0 by Sebastian Bergmann.
.F
Time: 0 seconds, Memory: 5.75Mb
There was 1 failure:
1) OutputTest::testExpectBarActualBaz
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'bar'
+'baz'
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
表 4.2中列举了用于对输出进行测试的各种方法。
表 4.2. 用于对输出进行测试的方法
方法 | 含义 |
---|---|
void expectOutputRegex(string $regularExpression) | 设定输出预期与 $regularExpression 正则表达式匹配。 |
void expectOutputString(string $expectedString) | 设定输出预期与 $expectedString 字符串相等。 |
bool setOutputCallback(callable $callback) | 设定回调函数,用于,比如说,将实际输出规范化。 |
注意
在严格模式下,本身产生输出的测试将会失败。
本节列举可用的各种断言方法。
assertArrayHasKey(mixed $key, array $array[, string $message = ''])
当 $array
不包含 $key
时,报告一个错误,错误讯息的内容由 $message
指定。
assertArrayNotHasKey()
是与之相反的断言,并接受相同的参数。
例 4.16: assertArrayHasKey() 的用法
<?php
class ArrayHasKeyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertArrayHasKey('foo', array('bar' => 'baz'));
}
}
?>
phpunit ArrayHasKeyTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) ArrayHasKeyTest::testFailure
Failed asserting that an array has the key 'foo'.
/home/sb/ArrayHasKeyTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertClassHasAttribute(string $attributeName, string $className[, string $message = ''])
当 $className::attributeName
不存在时,报告一个错误,错误讯息的内容由 $message
指定。
assertClassNotHasAttribute()
是与之相反的断言,并接受相同的参数。
例 4.17: assertClassHasAttribute() 的用法
<?php
class ClassHasAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertClassHasAttribute('foo', 'stdClass');
}
}
?>
phpunit ClassHasAttributeTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 4.75Mb
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()
是与之相反的断言,并接受相同的参数。
例 4.18: assertClassHasStaticAttribute() 的用法
<?php
class ClassHasStaticAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertClassHasStaticAttribute('foo', 'stdClass');
}
}
?>
phpunit ClassHasStaticAttributeTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 4.75Mb
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()
是两个便捷包装(convenience wrappers),以某个类或对象的 public
、 protected
或 private
属性为搜索范围。
例 4.19: assertContains() 的用法
<?php
class ContainsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContains(4, array(1, 2, 3));
}
}
?>
phpunit ContainsTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) ContainsTest::testFailure
Failed asserting that an array contains 4.
/home/sb/ContainsTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertContains(string $needle, string $haystack[, string $message = ''])
当 $needle
不是 $haystack
的子字符串时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.20: assertContains() 的用法
<?php
class ContainsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContains('baz', 'foobar');
}
}
?>
phpunit ContainsTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) ContainsTest::testFailure
Failed asserting that '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()
是两个便捷包装(convenience wrappers),以某个类或对象的 public
、 protected
或 private
属性为搜索范围。
例 4.21: assertContainsOnly() 的用法
<?php
class ContainsOnlyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContainsOnly('string', array('1', '2', 3));
}
}
?>
phpunit ContainsOnlyTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
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.
assertContainsOnlyInstancesOf(string $classname, Traversable|array $haystack[, string $message = ''])
当 $haystack
并非仅包含类 $classname
的实例时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.22: assertContainsOnlyInstancesOf() 的用法
<?php
class ContainsOnlyInstancesOfTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertContainsOnlyInstancesOf('Foo', array(new Foo(), new Bar(), new Foo()));
}
}
?>
phpunit ContainsOnlyInstancesOfTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) ContainsOnlyInstancesOfTest::testFailure
Failed asserting that Array ([0]=> Bar Object(...)) is an instance of class "Foo".
/home/sb/ContainsOnlyInstancesOfTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertCount($expectedCount, $haystack[, string $message = ''])
当 $haystack
中的元素数量不是 $expectedCount
时,报告一个错误,错误讯息的内容由 $message
指定。
assertNotCount()
是与之相反的断言,并接受相同的参数。
例 4.23: assertCount() 的用法
<?php
class CountTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertCount(0, array('foo'));
}
}
?>
phpunit CountTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 4.75Mb
There was 1 failure:
1) CountTest::testFailure
Failed asserting that actual size 1 matches expected size 0.
/home/sb/CountTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertEmpty(mixed $actual[, string $message = ''])
当 $actual
不是空的时,报告一个错误,错误讯息的内容由 $message
指定。
assertNotEmpty()
是与之相反的断言,并接受相同的参数。
assertAttributeEmpty()
和 assertAttributeNotEmpty()
是便捷包装(convenience wrappers), 可以应用于某个类或对象的某个 public
、 protected
或 private
属性。
例 4.24: assertEmpty() 的用法
<?php
class EmptyTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertEmpty(array('foo'));
}
}
?>
phpunit EmptyTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 4.75Mb
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(DOMElement $expectedElement, DOMElement $actualElement[, boolean $checkAttributes = FALSE, string $message = ''])
当 $actualElement
中的 DOMElement 的 XML 结构与 $expectedElement
中的 DOMElement的 XML 结构不相同时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.25: 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.8.0 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 0 matches expected 1.
/home/sb/EqualXMLStructureTest.php:22
3) EqualXMLStructureTest::testFailureWithDifferentChildrenCount
Number of child nodes of "foo" differs
Failed asserting that 1 matches expected 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(mixed $expected, mixed $actual[, string $message = ''])
当两个变量 $expected
与 $actual
不相等时,报告一个错误,错误讯息的内容由 $message
指定。
assertNotEquals()
是与之相反的断言,并接受相同的参数。
assertAttributeEquals()
和 assertAttributeNotEquals()
是便捷包装(convenience wrappers), 以某个类或对象的某个 public
、 protected
或 private
属性作为实际值来进行比较。
例 4.26: 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.8.0 by Sebastian Bergmann.
FFF
Time: 0 seconds, Memory: 5.25Mb
There were 3 failures:
1) EqualsTest::testFailure
Failed asserting that 0 matches expected 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])
当两个浮点数 $expected
和 $actual
之间的差值(的绝对值)大于 $delta
时,报告一个错误,错误讯息的内容由$message
指定。
关于为什么 $delta
参数是必须的,请阅读《关于浮点运算,每一位计算机科学家都应该知道的事实》
例 4.27: 将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.8.0 by Sebastian Bergmann.
.F
Time: 0 seconds, Memory: 5.75Mb
There was 1 failure:
1) EqualsTest::testFailure
Failed asserting that 1.1 matches expected 1.0.
/home/sb/EqualsTest.php:11
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
assertEquals(DOMDocument $expected, DOMDocument $actual[, string $message = ''])
当 $expected
和 $actual
这两个 DOMDocument 对象所表示的 XML 文档的无注释规范形式不相同时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.28: assertEquals()应用于 DOMDocument 对象时的用法
<?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.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) EqualsTest::testFailure
Failed asserting that two DOM documents 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 = ''])
当 $expected
和 $actual
这两个对象的属性值不相等时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.29: 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.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
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 = ''])
当 $expected
和 $actual
这两个数组不相等时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.30: 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.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
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(bool $condition[, string $message = ''])
当 $condition
为 TRUE
时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.31: assertFalse() 的用法
<?php
class FalseTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFalse(TRUE);
}
}
?>
phpunit FalseTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) FalseTest::testFailure
Failed asserting that true is false.
/home/sb/FalseTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertFileEquals(string $expected, string $actual[, string $message = ''])
当 $expected
所指定的文件与 $actual
所指定的文件其内容不同时,报告一个错误,错误讯息的内容由 $message
指定。
assertFileNotEquals()
是与之相反的断言,并接受相同的参数。
例 4.32: assertFileEquals() 的用法
<?php
class FileEqualsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFileEquals('/home/sb/expected', '/home/sb/actual');
}
}
?>
phpunit FileEqualsTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
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(string $filename[, string $message = ''])
当 $filename
所指定的文件不存在时,报告一个错误,错误讯息的内容由 $message
指定。
assertFileNotExists()
是与之相反的断言,并接受相同的参数。
例 4.33: assertFileExists() 的用法
<?php
class FileExistsTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertFileExists('/path/to/file');
}
}
?>
phpunit FileExistsTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 4.75Mb
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()
是便捷包装(convenience wrappers),以某个类或对象的某个 public
、protected
或 private
属性作为实际值来进行比较。
例 4.34: assertGreaterThan() 的用法
<?php
class GreaterThanTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertGreaterThan(2, 1);
}
}
?>
phpunit GreaterThanTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) GreaterThanTest::testFailure
Failed asserting that 1 is greater than 2.
/home/sb/GreaterThanTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertGreaterThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])
当 $actual
的值不大于且不等于 $expected
的值时,报告一个错误,错误讯息的内容由 $message
指定。
assertAttributeGreaterThanOrEqual()
是便捷包装(convenience wrappers),以某个类或对象的某个 public
、protected
或 private
属性作为实际值来进行比较。
例 4.35: assertGreaterThanOrEqual() 的用法
<?php
class GreatThanOrEqualTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertGreaterThanOrEqual(2, 1);
}
}
?>
phpunit GreaterThanOrEqualTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) GreatThanOrEqualTest::testFailure
Failed asserting that 1 is equal to 2 or is greater than 2.
/home/sb/GreaterThanOrEqualTest.php:6
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
assertInstanceOf($expected, $actual[, $message = ''])
当 $actual
不是 $expected
的实例时,报告一个错误,错误讯息的内容由 $message
指定。
assertNotInstanceOf()
是与之相反的断言,并接受相同的参数。
assertAttributeInstanceOf()
and assertAttributeNotInstanceOf()
是便捷包装(convenience wrappers), 可以应用于某个类或对象的某个 public
、 protected
或 private
属性。
例 4.36: assertInstanceOf() 的用法
<?php
class InstanceOfTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertInstanceOf('RuntimeException', new Exception);
}
}
?>
phpunit InstanceOfTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) InstanceOfTest::testFailure
Failed asserting that Exception Object (...) is an instance of class "RuntimeException".
/home/sb/InstanceOfTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertInternalType($expected, $actual[, $message = ''])
当 $actual
不是 $expected
所指明的类型时,报告一个错误,错误讯息的内容由 $message
指定。
assertNotInternalType()
是与之相反的断言,并接受相同的参数。
assertAttributeInternalType()
and assertAttributeNotInternalType()
是便捷包装(convenience wrappers), 可以应用于某个类或对象的某个 public
、 protected
或 private
属性.
例 4.37: assertInternalType() 的用法
<?php
class InternalTypeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertInternalType('string', 42);
}
}
?>
phpunit InternalTypeTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) InternalTypeTest::testFailure
Failed asserting that 42 is of type "string".
/home/sb/InternalTypeTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertJsonFileEqualsJsonFile(mixed $expectedFile, mixed $actualFile[, string $message = ''])
当 $actualFile
的值与 $expectedFile
的值不匹配时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.38: assertJsonFileEqualsJsonFile() 的用法
<?php
class JsonFileEqualsJsonFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertJsonFileEqualsJsonFile(
'path/to/fixture/file', 'path/to/actual/file');
}
}
?>
phpunit JsonFileEqualsJsonFileTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) JsonFileEqualsJsonFile::testFailure
Failed asserting that '{"Mascott":"Tux"}' matches JSON string "["Mascott", "Tux", "OS", "Linux"]".
/home/sb/JsonFileEqualsJsonFileTest.php:5
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.
assertJsonStringEqualsJsonFile(mixed $expectedFile, mixed $actualJson[, string $message = ''])
当 $actualJson
的值与 $expectedFile
的值不匹配时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.39: assertJsonStringEqualsJsonFile() 的用法
<?php
class JsonStringEqualsJsonFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertJsonStringEqualsJsonFile(
'path/to/fixture/file', json_encode(array("Mascott" => "ux"))
);
}
}
?>
phpunit JsonStringEqualsJsonFileTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) JsonStringEqualsJsonFile::testFailure
Failed asserting that '{"Mascott":"ux"}' matches JSON string "{"Mascott":"Tux"}".
/home/sb/JsonStringEqualsJsonFileTest.php:5
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.
assertJsonStringEqualsJsonString(mixed $expectedJson, mixed $actualJson[, string $message = ''])
当 $actualJson
的值与 $expectedJson
的值不匹配时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.40: assertJsonStringEqualsJsonString() 的用法
<?php
class JsonStringEqualsJsonStringTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertJsonStringEqualsJsonString(
json_encode(array("Mascott" => "Tux")), json_encode(array("Mascott" => "ux"))
);
}
}
?>
phpunit JsonStringEqualsJsonStringTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) JsonStringEqualsJsonStringTest::testFailure
Failed asserting that two objects are equal.
--- Expected
+++ Actual
@@ @@
stdClass Object (
- 'Mascott' => 'Tux'
+ 'Mascott' => 'ux'
)
/home/sb/JsonStringEqualsJsonStringTest.php:5
FAILURES!
Tests: 1, Assertions: 3, Failures: 1.
assertLessThan(mixed $expected, mixed $actual[, string $message = ''])
当 $actual
的值不小于 $expected
的值时,报告一个错误,错误讯息的内容由 $message
指定。
assertAttributeLessThan()
是便捷包装(convenience wrappers),以某个类或对象的某个 public
、 protected
或private
属性作为实际值来进行比较。
例 4.41: assertLessThan() 的用法
<?php
class LessThanTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertLessThan(1, 2);
}
}
?>
phpunit LessThanTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) LessThanTest::testFailure
Failed asserting that 2 is less than 1.
/home/sb/LessThanTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertLessThanOrEqual(mixed $expected, mixed $actual[, string $message = ''])
当 $actual
的值不小于且不等于 $expected
的值时,报告一个错误,错误讯息的内容由 $message
指定。
assertAttributeLessThanOrEqual()
是便捷包装(convenience wrappers),以某个类或对象的某个 public
、protected
或 private
属性作为实际值来进行比较。
例 4.42: assertLessThanOrEqual() 的用法
<?php
class LessThanOrEqualTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertLessThanOrEqual(1, 2);
}
}
?>
phpunit LessThanOrEqualTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) LessThanOrEqualTest::testFailure
Failed asserting that 2 is equal to 1 or is less than 1.
/home/sb/LessThanOrEqualTest.php:6
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
assertNull(mixed $variable[, string $message = ''])
当 $variable
不是 NULL
时,报告一个错误,错误讯息的内容由 $message
指定。
assertNotNull()
是与之相反的断言,并接受相同的参数。
例 4.43: assertNull() 的用法
<?php
class NullTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertNull('foo');
}
}
?>
phpunit NotNullTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) NullTest::testFailure
Failed asserting that 'foo' is null.
/home/sb/NotNullTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertObjectHasAttribute(string $attributeName, object $object[, string $message = ''])
当 $object->attributeName
不存在时,报告一个错误,错误讯息的内容由 $message
指定。
assertObjectNotHasAttribute()
是与之相反的断言,并接受相同的参数。
例 4.44: assertObjectHasAttribute() 的用法
<?php
class ObjectHasAttributeTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertObjectHasAttribute('foo', new stdClass);
}
}
?>
phpunit ObjectHasAttributeTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 4.75Mb
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()
是与之相反的断言,并接受相同的参数。
例 4.45: assertRegExp() 的用法
<?php
class RegExpTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertRegExp('/foo/', 'bar');
}
}
?>
phpunit RegExpTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) RegExpTest::testFailure
Failed asserting that 'bar' matches PCRE pattern "/foo/".
/home/sb/RegExpTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertStringMatchesFormat(string $format, string $string[, string $message = ''])
当 $string
与格式串 $format
不匹配时,报告一个错误,错误讯息的内容由 $message
指定。
assertStringNotMatchesFormat()
是与之相反的断言,并接受相同的参数。
例 4.46: assertStringMatchesFormat() 的用法
<?php
class StringMatchesFormatTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringMatchesFormat('%i', 'foo');
}
}
?>
phpunit StringMatchesFormatTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) StringMatchesFormatTest::testFailure
Failed asserting that 'foo' matches PCRE pattern "/^[+-]?\d+$/s".
/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(string $formatFile, string $string[, string $message = ''])
当 $string
与 $formatFile
的内容不匹配时,报告一个错误,错误讯息的内容由 $message
指定。
assertStringNotMatchesFormatFile()
是与之相反的断言,并接受相同的参数。
例 4.47: assertStringMatchesFormatFile() 的用法
<?php
class StringMatchesFormatFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringMatchesFormatFile('/path/to/expected.txt', 'foo');
}
}
?>
phpunit StringMatchesFormatFileTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) StringMatchesFormatFileTest::testFailure
Failed asserting that 'foo' matches PCRE pattern "/^[+-]?\d+
$/s".
/home/sb/StringMatchesFormatFileTest.php:6
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
assertSame(mixed $expected, mixed $actual[, string $message = ''])
当两个变量 $expected
和 $actual
的类型与值不完全相同时,报告一个错误,错误讯息的内容由 $message
指定。
assertNotSame()
是与之相反的断言,并接受相同的参数。
assertAttributeSame()
and assertAttributeNotSame()
是便捷包装(convenience wrappers), 以某个类或对象的某个 public
、 protected
或 private
属性作为实际值来进行比较。
例 4.48: assertSame() 的用法
<?php
class SameTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertSame('2204', 2204);
}
}
?>
phpunit SameTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) SameTest::testFailure
Failed asserting that 2204 is identical to '2204'.
/home/sb/SameTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertSame(object $expected, object $actual[, string $message = ''])
当两个变量 $expected
和 $actual
不是指向同一个对象的引用时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.49: assertSame() 应用于对象时的用法
<?php
class SameTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertSame(new stdClass, new stdClass);
}
}
?>
phpunit SameTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 4.75Mb
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])
将 CSS 选择器 $selector
应用于 DOMNode $actual
,当匹配元素的数量与 $count
不相符时,报告一个错误,错误讯息的内容由 $message
指定。
$count
可以是以下类型之一:
boolean
:断言存在符合条件的元素(TRUE
)或不存在这样的元素(FALSE
)。integer
:断言符合条件的元素的数量。array
:断言符合条件的元素的数量所在的区间,用<
、>
、<=
和>=
作为键名来指定相关信息。
例 4.50: 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.8.0 by Sebastian Bergmann.
FFFF
Time: 0 seconds, Memory: 5.50Mb
There were 4 failures:
1) SelectCountTest::testAbsenceFailure
Failed asserting that true is false.
/home/sb/SelectCountTest.php:12
2) SelectCountTest::testPresenceFailure
Failed asserting that false is true.
/home/sb/SelectCountTest.php:17
3) SelectCountTest::testExactCountFailure
Failed asserting that 3 matches expected 5.
/home/sb/SelectCountTest.php:22
4) SelectCountTest::testRangeFailure
Failed asserting that false is true.
/home/sb/SelectCountTest.php:27
FAILURES!
Tests: 4, Assertions: 4, Failures: 4.
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.51: 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.8.0 by Sebastian Bergmann.
FFFF
Time: 0 seconds, Memory: 5.50Mb
There were 4 failures:
1) SelectEqualsTest::testAbsenceFailure
Failed asserting that true is false.
/home/sb/SelectEqualsTest.php:12
2) SelectEqualsTest::testPresenceFailure
Failed asserting that false is true.
/home/sb/SelectEqualsTest.php:17
3) SelectEqualsTest::testExactCountFailure
Failed asserting that 2 matches expected 5.
/home/sb/SelectEqualsTest.php:22
4) SelectEqualsTest::testRangeFailure
Failed asserting that false is true.
/home/sb/SelectEqualsTest.php:27
FAILURES!
Tests: 4, Assertions: 4, Failures: 4.
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.52: 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.8.0 by Sebastian Bergmann.
FFFF
Time: 0 seconds, Memory: 5.50Mb
There were 4 failures:
1) SelectRegExpTest::testAbsenceFailure
Failed asserting that true is false.
/home/sb/SelectRegExpTest.php:12
2) SelectRegExpTest::testPresenceFailure
Failed asserting that false is true.
/home/sb/SelectRegExpTest.php:17
3) SelectRegExpTest::testExactCountFailure
Failed asserting that 2 matches expected 5.
/home/sb/SelectRegExpTest.php:22
4) SelectRegExpTest::testRangeFailure
Failed asserting that false is true.
/home/sb/SelectRegExpTest.php:27
FAILURES!
Tests: 4, Assertions: 4, Failures: 4.
assertStringEndsWith(string $suffix, string $string[, string $message = ''])
当 $string
不以 $suffix
结尾时,报告一个错误,错误讯息的内容由 $message
指定。
assertStringEndsNotWith()
是与之相反的断言,并接受相同的参数。
例 4.53: assertStringEndsWith() 的用法
<?php
class StringEndsWithTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringEndsWith('suffix', 'foo');
}
}
?>
phpunit StringEndsWithTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 1 second, Memory: 5.00Mb
There was 1 failure:
1) StringEndsWithTest::testFailure
Failed asserting that '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()
是与之相反的断言,并接受相同的参数。
例 4.54: assertStringEqualsFile() 的用法
<?php
class StringEqualsFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringEqualsFile('/home/sb/expected', 'actual');
}
}
?>
phpunit StringEqualsFileTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
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(string $prefix, string $string[, string $message = ''])
当 $string
不以 $prefix
开头时,报告一个错误,错误讯息的内容由 $message
指定。
assertStringStartsNotWith()
是与之相反的断言,并接受相同的参数。
例 4.55: assertStringStartsWith() 的用法
<?php
class StringStartsWithTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertStringStartsWith('prefix', 'foo');
}
}
?>
phpunit StringStartsWithTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) StringStartsWithTest::testFailure
Failed asserting that '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
属性值。tag
:节点的类型必须与对应值相匹配。attributes
:节点的属性必须与$attributes
关联数组中所描述的对应值相匹配。content
:文本内容必须与指定值相匹配。parent
:节点的父节点必须匹配于$parent
关联数组。child
: 节点的直接子节点(immediate children,即节点的下一级节点)中要至少有一个与$child
关联数组所描述的准则一致。ancestor
:节点的祖先节点中要至少有一个与$ancestor
关联数组所描述的准则一致。descendant
:节点的后代节点中要至少有一个与$descendant
关联数组所描述的准则一致。children
:关联数组,节点的子节点的计数信息。count
:匹配的子节点数量必须等于此数字。less_than
:匹配的子节点数量必须小于此数字。greater_than
: 匹配的子节点数量必须大于此数字。only
:另一个关联数组,由用来对子节点进行匹配的键名组成,只有匹配的子节点才会进行计数。
assertNotTag()
是与之相反的断言,并接受相同的参数。
例 4.56: assertTag() 的用法
<?php
// 这个匹配器断言存在 id="my_id" 的元素。
$matcher = array('id' => 'my_id');
// 这个匹配器断言存在 "span" 标签。
$matcher = array('tag' => 'span');
// 这个匹配器断言存在内容为 "Hello World" 的 "span" 标签。
$matcher = array('tag' => 'span', 'content' => 'Hello World');
// 这个匹配器断言存在其内容与正则表达式模式相匹配的 "span" 标签。
$matcher = array('tag' => 'span', 'content' => 'regexp:/Try P(HP|ython)/');
// 这个匹配器断言存在class属性为 "list" 的 "span"。
$matcher = array(
'tag' => 'span',
'attributes' => array('class' => 'list')
);
// 这个匹配器断言存在父元素为 "div" 的 "span"。
$matcher = array(
'tag' => 'span',
'parent' => array('tag' => 'div')
);
// 这个匹配器断言存在某个 "span",其祖先元素中有 "table"。
$matcher = array(
'tag' => 'span',
'ancestor' => array('tag' => 'table')
);
// 这个匹配器断言存在某个 "span",其直接子节点中至少有一个 "em"。
$matcher = array(
'tag' => 'span',
'child' => array('tag' => 'em')
);
// 这个匹配器断言存在某个 "span",其所有后代子节点中存在 "strong" 标签。
$matcher = array(
'tag' => 'span',
'descendant' => array('tag' => 'strong')
);
// 这个匹配器断言存在某个 "span",其直接子节点中包含有 5 到 10 个 "em" 标签。
$matcher = array(
'tag' => 'span',
'children' => array(
'less_than' => 11,
'greater_than' => 4,
'only' => array('tag' => 'em')
)
);
// 这个匹配器断言存在一个 "div",其祖先元素中有 "ul",且其父元素是 class="enum" 的 "li",
// 且其后代子节点中存在一个 id="my_test" 同时文本内容为 "Hello World" 的 "span"。
$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()
方法对其进行评定。 例 4.57展示了如何用 logicalNot()
和 equalTo()
约束条件来表达与 assertNotEquals()
等价的断言。
assertThat(mixed $value, PHPUnit_Framework_Constraint $constraint[, $message = ''])
当 $value
与 $constraint
不匹配时,报告一个错误,错误讯息的内容由 $message
指定。
例 4.57: 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.3列举了所有可用的 PHPUnit_Framework_Constraint
类。
表 4.3. 约束条件
约束条件 | 含义 |
---|---|
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) | 此约束断言所评定的array 或实现了Iterator 接口的对象包含有给定值。 |
PHPUnit_Framework_Constraint_TraversableContainsOnly containsOnly(string $type) | 此约束断言所评定的array 或实现了Iterator 接口的对象仅包含给定类型的值。 |
PHPUnit_Framework_Constraint_TraversableContainsOnly containsOnlyInstancesOf(string $classname) | 此约束断言所评定的array 或实现了Iterator 接口的对象仅包含给定类名的类的实例。 |
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) | 此约束断言所评定的类具有给定静态属性。 |
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() | 逻辑与。 |
logicalNot(PHPUnit_Framework_Constraint $constraint) | 逻辑非。 |
logicalOr() | 逻辑或。 |
logicalXor() | 逻辑异或。 |
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
指定。
例 4.58: assertTrue() 的用法
<?php
class TrueTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertTrue(FALSE);
}
}
?>
phpunit TrueTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) TrueTest::testFailure
Failed asserting that false is true.
/home/sb/TrueTest.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile[, string $message = ''])
当 $actualFile
中的 XML 文档与 $expectedFile
中的 XML 文档不相等时,报告一个错误,错误讯息的内容由$message
指定。
assertXmlFileNotEqualsXmlFile()
是与之相反的断言,并接受相同的参数。
例 4.59: 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.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) XmlFileEqualsXmlFileTest::testFailure
Failed asserting that two DOM documents 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(string $expectedFile, string $actualXml[, string $message = ''])
当 $actualXml
中的 XML 文档与 $expectedFile
中的 XML 文档不相等时,报告一个错误,错误讯息的内容由 $message
指定。
assertXmlStringNotEqualsXmlFile()
是与之相反的断言,并接受相同的参数。
例 4.60: assertXmlStringEqualsXmlFile() 的用法
<?php
class XmlStringEqualsXmlFileTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlStringEqualsXmlFile(
'/home/sb/expected.xml', '<foo><baz/></foo>');
}
}
?>
phpunit XmlStringEqualsXmlFileTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) XmlStringEqualsXmlFileTest::testFailure
Failed asserting that two DOM documents 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(string $expectedXml, string $actualXml[, string $message = ''])
当 $actualXml
中的 XML 文档与 $expectedXml
中的 XML 文档不相等时,报告一个错误,错误讯息的内容由 $message
指定。
assertXmlStringNotEqualsXmlString()
是与之相反的断言,并接受相同的参数。
例 4.61: assertXmlStringEqualsXmlString() 的用法
<?php
class XmlStringEqualsXmlStringTest extends PHPUnit_Framework_TestCase
{
public function testFailure()
{
$this->assertXmlStringEqualsXmlString(
'<foo><bar/></foo>', '<foo><baz/></foo>');
}
}
?>
phpunit XmlStringEqualsXmlStringTest
PHPUnit 3.8.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.00Mb
There was 1 failure:
1) XmlStringEqualsXmlStringTest::testFailure
Failed asserting that two DOM documents are equal.
--- Expected
+++ Actual
@@ @@
<?xml version="1.0"?>
<foo>
- <bar/>
+ <baz/>
</foo>
/home/sb/XmlStringEqualsXmlStringTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
当有测试失败时,PHPUnit 全力提供尽可能多的有助于找出问题所在的上下文信息。
例 4.62: 数组比较失败时生成的错误相关信息输出
<?php
class ArrayDiffTest extends PHPUnit_Framework_TestCase
{
public function testEquality() {
$this->assertEquals(
array(1,2,3 ,4,5,6),
array(1,2,33,4,5,6)
);
}
}
?>
phpunit ArrayDiffTest
PHPUnit 3.6.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) ArrayDiffTest::testEquality
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
0 => 1
1 => 2
- 2 => 3
+ 2 => 33
3 => 4
4 => 5
5 => 6
)
/home/sb/ArrayDiffTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
在这个例子中,数组中只有一个值不同,但其他值也都同时显示出来,以提供关于错误发生的位置的上下文信息。
当生成的输出很长而难以阅读时,PHPUnit 将对其进行分割,并在每个差异附近提供少数几行上下文信息。
例 4.63: 长数组比较失败时生成的错误相关信息输出
<?php
class LongArrayDiffTest extends PHPUnit_Framework_TestCase
{
public function testEquality() {
$this->assertEquals(
array(0,0,0,0,0,0,0,0,0,0,0,0,1,2,3 ,4,5,6),
array(0,0,0,0,0,0,0,0,0,0,0,0,1,2,33,4,5,6)
);
}
}
?>
phpunit LongArrayDiffTest
PHPUnit 3.6.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) LongArrayDiffTest::testEquality
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
13 => 2
- 14 => 3
+ 14 => 33
15 => 4
16 => 5
17 => 6
)
/home/sb/LongArrayDiffTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
当比较失败时,PHPUnit 为输入值建立文本表示,然后以此进行对比。这种实现导致在差异指示中显示出来的问题可能比实际上存在的多。
这种情况只出现在对数组或者对象使用 assertEquals 或其他“弱”比较函数时。
例 4.64: 当使用弱比较时在生成的差异结果中出现的边缘情况
<?php
class ArrayWeakComparisonTest extends PHPUnit_Framework_TestCase
{
public function testEquality() {
$this->assertEquals(
array(1 ,2,3 ,4,5,6),
array('1',2,33,4,5,6)
);
}
}
?>
phpunit ArrayWeakComparisonTest
PHPUnit 3.6.0 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 5.25Mb
There was 1 failure:
1) ArrayWeakComparisonTest::testEquality
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 0 => 1
+ 0 => '1'
1 => 2
- 2 => 3
+ 2 => 33
3 => 4
4 => 5
5 => 6
)
/home/sb/ArrayWeakComparisonTest.php:7
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
在这个例子中,第一个索引项中的 1
和 '1'
在报告中被视为不同,但 assertEquals 仍认为这两个值是匹配的。