當(dāng)按照 ?$actual->$method($expected)
? 判斷出 ?$actual
? 不等于 ?$expected
? 時(shí)報(bào)告錯(cuò)誤,錯(cuò)誤訊息由 ?$message
? 指定。
在對(duì)象上使用 ?assertEquals()
?(以及其否斷言形式 ?assertNotEquals()
?)而不注冊(cè)自定義比較器來(lái)定制對(duì)象的比較方式是一種不良做法。但是,很不幸地,為每個(gè)要在測(cè)試中進(jìn)行斷言的對(duì)象都實(shí)現(xiàn)自定義比較器無(wú)論如何至少也是不方便的。
自定義比較器最常見(jiàn)的用例是值對(duì)象。這類對(duì)象一般都有一個(gè) ?equals(self $other): bool
? 方法(或者名稱不同的類似方法)用于比較這個(gè)同為值對(duì)象類型的兩個(gè)實(shí)例。對(duì)于這類用例,?assertObjectEquals()
? 讓自定義對(duì)象比較變得很方便:
示例 1.21 assertObjectEquals() 的用法
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class SomethingThatUsesEmailTest extends TestCase
{
public function testSomething(): void
{
$a = new Email('user@example.org');
$b = new Email('user@example.org');
$c = new Email('user@example.com');
// This passes
$this->assertObjectEquals($a, $b);
// This fails
$this->assertObjectEquals($a, $c);
}
}
示例 1.22 帶有 equals() 方法的 Email 值對(duì)象
<?php declare(strict_types=1);
final class Email
{
private string $email;
public function __construct(string $email)
{
$this->ensureIsValidEmail($email);
$this->email = $email;
}
public function asString(): string
{
return $this->email;
}
public function equals(self $other): bool
{
return $this->asString() === $other->asString();
}
private function ensureIsValidEmail(string $email): void
{
// ...
}
}
$ phpunit EqualsTest
PHPUnit latest.0 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 00:00.017, Memory: 4.00 MB
There was 1 failure:
1) SomethingThatUsesEmailTest::testSomething
Failed asserting that two objects are equal.
The objects are not equal according to Email::equals().
/home/sb/SomethingThatUsesEmailTest.php:16
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
請(qǐng)注意:
$actual
? 對(duì)象必須存在名叫 ?$method
? 的方法$expected
? 對(duì)象必須與這個(gè)聲明的類型兼容bool
?的返回類型如果以上假設(shè)中的任何一條不滿足,或 ?$actual->$method($expected)
? 返回 ?false
?,則斷言失敗。
更多建議: