Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: How to assert that a class extends another class?

Tags:

php

phpunit

In my PHPUnit test, I would like to assert that the class that I am testing extends another class. How can I do this with PHPUnit?

like image 272
Andrew Avatar asked Oct 06 '11 19:10

Andrew


People also ask

How do you test a class that extends another class?

If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class) Class#isAssignableFrom(Class) also returns true if both classes are same. To find if an object is instance of a class use instanceof operator.

What is assert in PHPUnit?

The assertSame() function is a builtin function in PHPUnit and is used to assert whether the actually obtained value is the same as the expected value or not. This assertion will return true in the case if the expected value is the same as the actual value else returns false.


3 Answers

Use assertInstanceOf() instead of PHP's built in instanceof operator or functions so that you get a meaningful failure message.

function testInstanceOf() {
    $obj = new Foo;
    self::assertInstanceOf('Bar', $obj);
}

...

Failed asserting that <Foo> is an instance of class "Bar".
like image 92
David Harkness Avatar answered Oct 04 '22 21:10

David Harkness


Or also you should use this assert like this:

    $this->assertSame(
        'Symfony\Component\Form\AbstractType',
        get_parent_class('AppBundle\Form\CarType'),
        'The form does not extend the AbstractType class'
        );
like image 23
jjoselon Avatar answered Oct 04 '22 22:10

jjoselon


What about using instanceof?

-> http://php.net/manual/en/internals2.opcodes.instanceof.php

like image 45
MasterCassim Avatar answered Oct 04 '22 20:10

MasterCassim