Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit forces me to require classes before asserting instance of

Tags:

php

phpunit

I am testing an object that returns an instance of another class. Internally, that class calls require_once. However, when I try to check that the object returned is of that type I get this message:

InvalidArgumentException: Argument #1 of PHPUnit_Framework_Assert::assertInstanceOf() must be a class or interface name

This message goes away once I call require_once again in my test before the call to assertInstanceOf. This doesn't seem right. It seems like PHPUnit should be smart enough to know that the class is already loaded, so I shouldn't have to load it again. Am I thinking of this wrong? Do I have my PHPUnit configured wrong? Is there a way to avoid requiring this class again in my test?

like image 327
Andrew Avatar asked May 02 '12 20:05

Andrew


2 Answers

Be sure to use the full namespace:

$this->assertInstanceOf('\Namespace\Subnamespace\MyClass', $obj);
like image 97
Tyler Collier Avatar answered Sep 22 '22 01:09

Tyler Collier


Your unit may be similar to this:

$this->assertInstanceOf('MyOtherClass', 
    $this->object->someFunctionReturnsOtherClass());

This is alright except here, Note: phpunit method is called BEFORE your object. Since you said, your object already internally does a require_once means till your method got called, 'MyOtherClass' stays as a undefined class. Thats exactly what happened. Phpunit function prepared to check using 'MyOtherClass' and found it is undefined!

The object's own require_once never even got called. That is why you have to do a call yourself before. Its similar if you use a statement like true == $returnObject instanceOf MyOtherClass which will return same error since while parsing PHP failed to find the class definition.

like image 25
thevikas Avatar answered Sep 19 '22 01:09

thevikas