php PHPUnit、模拟接口和 instanceof
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3250503/
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, mocked interfaces, and instanceof
提问by Bryan M.
Sometimes in my code, I'll check to see if a particular object implements an interface:
有时在我的代码中,我会检查一个特定的对象是否实现了一个接口:
if ($instance instanceof Interface) {};
However, creating mocks of said interface in PHPUnit, I can't seem to pass that test.
但是,在 PHPUnit 中创建所述接口的模拟,我似乎无法通过该测试。
// class name is Mock_Interface_431469d7, does not pass above check
$instance = $this->getMock('Interface');
I understand that having a class named Interface is different from a class implementing Interface, but I'm not sure how to get deal with this.
我知道有一个名为 Interface 的类与实现 Interface 的类不同,但我不确定如何处理这个问题。
Am I forced to mock a concrete class that implements Interface? Wouldn't that defeat the purpose of using an interface for portability?
我是否被迫模拟一个实现接口的具体类?这不会违背使用接口实现可移植性的目的吗?
Thanks
谢谢
回答by Brendon-Van-Heyzen
there is also assertInstanceOf as of 3.5.0
从 3.5.0 开始,还有 assertInstanceOf
Example:
例子:
$this->assertInstanceOf('\Models\User', $this->userService->findById(1));
回答by martinvium
This works for me:
这对我有用:
$mock = $this->getMock('TestInterface');
$this->assertTrue($mock instanceof TestInterface);
Maybe it's a typo or maybe $instance isn't what you think it is?
也许这是一个错字,或者 $instance 不是你认为的那样?
回答by Йося Гисем
Use PhpUnit function assertInstanceOf.
使用 PhpUnit 函数 assertInstanceOf。
Example:
例子:
$this->assertInstanceOf(ResponseInterface::class, $signInResponse);

