PHPUnit: assertInstanceOf() not working

PhpPhpunitAssertAssertions

Php Problem Overview


I need to check if a variable is an object of the User type. User is my class $user my object

$this->assertInstanceOf($user,User);

This is not working, I have a use of undefined constant User - assumed 'User'

Thanks in advance for your help

Php Solutions


Solution 1 - Php

http://apigen.juzna.cz/doc/sebastianbergmann/phpunit/function-assertInstanceOf.html

I think you are using this function wrong. Try:

$this->assertInstanceOf('User', $user);

Solution 2 - Php

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.

$this->assertInstanceOf(User::class, $user);

Solution 3 - Php

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.

$testedObj = new ObjectToTest();
$this->assertInstanceOf(
    get_class($testedObj), 
    $testedObj->setSomething('someValue'),
    'Setter is not returning $this reference'
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1173169View Question on Stackoverflow
Solution 1 - PhpMantasView Answer on Stackoverflow
Solution 2 - PhpRápli AndrásView Answer on Stackoverflow
Solution 3 - PhpRafal KozlowskiView Answer on Stackoverflow