How to write custom PHPUnit assertion that behaves like built-in assertion?

陌路散爱 提交于 2019-12-03 14:12:36

My first guess of the problem (that you're not using one of the PHPUnit_Framework_Constraint_* objects and self::assertThat) turned out to be completely irrelevant! The actual answer is that phpUnit helpfully filters away from the stack trace anything in its own codebase, and just leaves functions in user space!

The code that does this can be found in /path/to/PHPUnit/Util/Filter.php (where /path/to/ is /usr/share/php on my machine) and the functions of interest are getFilteredStacktrace and isFiltered.

If you'd like to control this behaviour, then put your custom asserts into a class derived from PHPUnit_Framework_TestCase, then derive your tests from that class. In your custom class file put a call somewhere to addFileToFilter, as shown here:

class My_Base_TestCase extends PHPUnit_Framework_TestCase{
  public static function assertFoo($expected, $actual) {
    self::assertEquals($expected, $actual); 
  }
}

PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT');

Then in another file you have:

class CustomTest extends My_Base_TestCase{

  /** */
  public function testSomething2(){
    $this->assertFoo( 8,  5+4 );
  }
}

and it will behave just like the built-in assertEquals().

DISCLAIMER: This is using undocumented behaviour! I'll try and find out if this mechanism is going to be reasonably future-proof.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!