PHPUnit9.0 斷言-assertObjectEquals()

2022-03-24 10:21 更新

assertObjectEquals(object $expected, object $actual, string $method = ' equals', string $message =''])

PHPUnit9.0 斷言集合PHPUnit9.0 斷言集合

當按照 ?$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?,則斷言失敗。


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號