How do I write my own PHPUnit statement that behaves like an inline statement?

How can I write a custom statement, for example assertFoo($expected, $actual) , which behaves like inline statements regarding a stack trace error?

Currently, I have the following method installed (inside a class that extends PHPUnit_Framework_TestCase ):

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

If I called this from the test and the test failed, I get two items in the call stack:

 1) PreferencesTest::testSignupTeacher Failed asserting that 5 matches expected 3. /vagrant/myproject/tests/integration/PreferencesTest.php:17 /vagrant/myproject/tests/integration/PreferencesTest.php:136 

Line 17 is where assertFoo() calls the built-in assertEquals() and fails; line 136 exists assertFoo() .

If I change the test to call assertEquals() directly, I get only one:

 1) PreferencesTest::testSignupTeacher Failed asserting that 3 is true. /vagrant/myproject/tests/integration/PreferencesTest.php:136 

There is documentation in the manual , but it does not seem to cover this.

+6
source share
1 answer

My first assumption about the problem (that you are not using one of the PHPUnit_Framework_Constraint_* and self::assertThat ) turned out to be completely inappropriate! The actual answer is that phpUnit helps filter out something in its own code base from the stack trace and simply leaves functions in user space!

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

If you want to control this behavior, add your custom statements to a class derived from PHPUnit_Framework_TestCase , and then derive tests from this class. In your custom class file, place the call somewhere in addFileToFilter , as shown below:

 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 exactly like the built-in assertEquals() .

DISCLAIMER: Use of undocumented behavior! I will try to find out if this mechanism is reasonable for the future.

+3
source

Source: https://habr.com/ru/post/921787/


All Articles