PHPUnit9.0 断言-assertObjectEquals()
2022-03-24 10:21 更新
assertObjectEquals(object $expected, object $actual, string $method = ' equals', string $message =''])
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,则断言失败。
以上内容是否对您有帮助:

免费 AI IDE


更多建议: