Why are concrete statements better than general statements in PHPUnit?

Please excuse my ignorance; I'm still new to unit testing.

Can someone explain why ..

$this->assertGreaterThan( 2, $result );

.. better than..

$this->assertTrue( $result > 2 );

.. (as well as all other specific approval methods)?

Thanks!

+4
source share
3 answers

If you showed your mom / dad / uncle, then assertGreaterThan much more intuitive. Plus a failed message for isGreaterThan will be much better

 "1 was not greater than 2" 

or

 "false was not true" 

Which one is more expressive?

+12
source

Actually, the best way provides better readability and better error messages: use PHPUnit based on approval functions or the Hamcrest Library .

 assertThat(count($users), greaterThan(2)); >> Expected: greater than 2 >> but: was 1 

or

 assertThat($users, arrayWithSize(greaterThan(2))); >> Expected: array with size greater than 2 >> but: was array with size 1 

You can always provide a readable error message with any statement by adding a line as the first parameter to the statement methods or the Hamcrest assertThat function or the third parameter to the PHPUnit assertThat function:

 self::assertTrue('At least one user found', !empty($users)); >> At least one user found >> Expected: true >> but: false 

or

 assertThat('At least one user found', !empty($users), is(true)); >> At least one user found >> Expected: true >> but: false 
+3
source

better than...

Who is speaking? Both are good. In both cases, the readability is different, but none of them is especially great. You can improve it with some variable extraction:

 $minimumValue = 2; $this->assertGreaterThan($minimumValue, $result); 

and

 $resultGreaterThanMinimumValue = $result > 2; $this->assertTrue($resultGreaterThanMinimumValue); 

This is still not ideal (since these statements are not readable like a sentence in English), but neither of these two approaches is better.

0
source

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


All Articles