PHPUnit, mocked interfaces, and instanceof
Solution 1
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?
Solution 2
there is also assertInstanceOf as of 3.5.0
Example:
$this->assertInstanceOf('\Models\User', $this->userService->findById(1));
Solution 3
Use PhpUnit function assertInstanceOf.
Example:
$this->assertInstanceOf(ResponseInterface::class, $signInResponse);
learner
I'm a web developer who writes PHP / Zend Framework apps by day and Rails apps by night. I'm also a CSS ninja and javascript dabbler. If I'm not programming a site, I'm probably working on IA charts on UI design. I like to bring order out of chaos.
Updated on January 25, 2020Comments
-
learner over 4 years
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.
// 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.
Am I forced to mock a concrete class that implements Interface? Wouldn't that defeat the purpose of using an interface for portability?
Thanks
-
learner almost 14 yearsYep, cooler heads prevail. After a night of full sleep, I realized I wasn't using the fully qualified namespace when mocking the object.
-
stefgosselin almost 13 yearsThis is recommended way of type checking.
-
kapad over 10 yearsSlightly different use case, but can I check if an instance is an instance of a class or of a mock of the class.
-
Dmitry over 10 years@kapad You see, this is the main point of Polymorphism that you don't have to know if the current object is and instance of class or a mock. If you still need to know, then you do something wrong. P.S. Just FYI you can use get_class function to know the exact class name of the object
-
kapad over 10 years@dvaffection Already solved using get_class(). I wanted to test, and definitely do something wrong. The point was to check an edge case.
-
emix about 9 yearsIn addition to @stefgosselin answer, this is recommended way of type checking, because you get better, self explaining error messages. Compare
failed asserting that object is instance of Class
tofail asserting that false is true
. -
Vegard Larsen over 7 yearsAs of PHP 5.5 you can use
\Models\User::class
instead of'\Models\User'
, which makes it a lot easier to do refactoring.