W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
當按照 ?$actual->$method($expected)
? 判斷出 ?$actual
? 不等于 ?$expected
? 時報告錯誤,錯誤訊息由 ?$message
? 指定。
在對象上使用 ?assertEquals()
?(以及其否斷言形式 ?assertNotEquals()
?)而不注冊自定義比較器來定制對象的比較方式是一種不良做法。但是,很不幸地,為每個要在測試中進行斷言的對象都實現自定義比較器無論如何至少也是不方便的。
自定義比較器最常見的用例是值對象。這類對象一般都有一個 ?equals(self $other): bool
? 方法(或者名稱不同的類似方法)用于比較這個同為值對象類型的兩個實例。對于這類用例,?assertObjectEquals()
? 讓自定義對象比較變得很方便:
示例 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 值對象
<?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.
請注意:
$actual
? 對象必須存在名叫 ?$method
? 的方法$expected
? 對象必須與這個聲明的類型兼容bool
?的返回類型如果以上假設中的任何一條不滿足,或 ?$actual->$method($expected)
? 返回 ?false
?,則斷言失敗。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: