Search code examples
phpfunctionphpunitassert

HowTo PHPUnit assertFunction


I was wondering if how I can verify if a 'class' has a Function. assertClassHasAttribute does not work, it's normal since a Function is not an Attribute.


Solution

  • When there's not an assertion method provided by PHPUnit I either create it or use one of the lower-level assertions with a verbose message:

    $this->assertTrue(
      method_exists($myClass, 'myFunction'), 
      'Class does not have method myFunction'
    );
    

    assertTrue() is as basic as you can get. It allows a great deal of flexibility because you can use any built-in php function that returns a bool value for your test. Consequently, when the test fails the error/failure message isn't helpful at all. Something like Failed asserting that <FALSE> is TRUE. That's why it's important to pass the second param to assertTrue() detailing why the test failed.