PHPUnit:当将类型作为第二个参数作为非字符串传递时,assertInstanceOf() 不起作用

问题描述 投票:0回答:3

我需要检查变量是否是 User 类型的对象。

User是我的班级

$user
我的对象

$this->assertInstanceOf($user, User);

这不起作用。我有以下错误:

use of undefined constant User - assumed 'User'

php phpunit assert assertion
3个回答
150
投票

https://docs.phpunit.de/en/9.5/assertions.html#assertinstanceof

我认为你使用这个功能是错误的。尝试:

$this->assertInstanceOf('User', $user);

PHP 5.5 开始,您还可以使用:

$this->assertInstanceOf(User::class, $user);

(来自评论中的@james2doyle。)


66
投票

尽可能使用

::class
总是一个好主意。如果您习惯了此标准,则不必使用 FQCN(完全限定类名)或转义反斜杠。此外,如果 IDE 知道这里的
User
不仅仅是一个字符串,而是一个类,那么它们可以提供更好的功能。

$this->assertInstanceOf(User::class, $user);

7
投票

或者你可以使用类似的东西:

$this->assertInstanceOf(get_class($expectedObject), $user);

我通常在检查时使用它,即 setter 方法是否返回对 self 的引用。

$testedObj = new ObjectToTest();
$this->assertInstanceOf(
    get_class($testedObj),
    $testedObj->setSomething('someValue'),
    'Setter is not returning $this reference'
);
© www.soinside.com 2019 - 2024. All rights reserved.