PHPUnit provides the following function to assert whether an object is an instance of a class:
assertInstanceOf($expected, $actual[, $message = ''])
The first parameter $expected
is the name of a class (string). The second parameter $actual
is the object to be tested. $message
is an optional string you can provide in case it fails.
Let's start with a simple Foo class:
class Foo {
}
Somewhere else in a namespace Crazy
, there is a Bar
class.
namespace Crazy
class Bar {
}
Now, let's write a basic test case that would check an object for these classes
use Crazy\Bar;
class sampleTestClass extends PHPUnit_Framework_TestCase
{
public function test_instanceOf() {
$foo = new Foo();
$bar = new Bar();
// this would pass
$this->assertInstanceOf("Foo",$foo);
// this would pass
$this->assertInstanceOf("\\Crazy\\Bar",$bar);
// you can also use the ::class static function that returns the class name
$this->assertInstanceOf(Bar::class, $bar);
// this would fail
$this->assertInstanceOf("Foo", $bar, "Bar is not a Foo");
}
}
Note that PHPUnit gets grumpy if you send in a classname that doesn't exist.