php PHPUnit:assertInstanceOf() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16833923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHPUnit: assertInstanceOf() not working
提问by Mantas
I need to check if a variable is an object of the User type.
User is my class $user
my object
我需要检查一个变量是否是 User 类型的对象。用户是我的班级$user
我的对象
$this->assertInstanceOf($user,User);
This is not working, I have a use of undefined constant User - assumed 'User'
这不起作用,我使用了未定义的常量用户 - 假设为“用户”
Thanks in advance for your help
在此先感谢您的帮助
回答by Mantas
http://apigen.juzna.cz/doc/sebastianbergmann/phpunit/function-assertInstanceOf.html
http://apigen.juzna.cz/doc/sebastianbergmann/phpunit/function-assertInstanceOf.html
I think you are using this function wrong. Try:
我认为您使用此功能是错误的。尝试:
$this->assertInstanceOf('User', $user);
回答by Rápli András
It's always a good idea to use ::class
wherever you can. If you get used to this standard, you don't have to use FQCNs (fully qualified classnames), or escape backslashes. Also, IDEs provide better functionality if they know that User
here is not just a string, but rather a class.
::class
随时随地使用总是一个好主意。如果您习惯了此标准,则不必使用 FQCN(完全限定的类名)或转义反斜杠。此外,如果 IDE 知道User
这里不仅仅是一个字符串,而是一个类,它们会提供更好的功能。
$this->assertInstanceOf(User::class, $user);
回答by Rafal Kozlowski
Or You can use something like:
或者你可以使用类似的东西:
$this->assertInstanceOf(get_class($expectedObject), $user);
I usually use this when I'm checking i.e. if setter method is returning reference to self.
我通常在检查时使用它,即 setter 方法是否返回对 self 的引用。
$testedObj = new ObjectToTest();
$this->assertInstanceOf(
get_class($testedObj),
$testedObj->setSomething('someValue'),
'Setter is not returning $this reference'
);