Please excuse my ignorance; I am still new to the unit testing realm.
Can someone explain why..
$this->assertGreaterThan( 2, $result );
..is better than..
$this->assertTrue( $result > 2 );
..(and likewise, all the other specific assert methods)?
Thanks!
The assertEquals() function is a builtin function in PHPUnit and is used to assert whether the actual obtained value is equals to 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.
phpunit Assertions Assert an Exception is ThrownexpectException($exception) expectExceptionMessage($message) expectExceptionCode($code)
And usually, one test method only has one assert at the end of it. But what happens if you have multiple asserts in a unit test? If you have more than one assert in a unit test, the unit test will be completed successfully if all assertions are met.
The get method makes a GET request into the application, while the assertStatus method asserts that the returned response should have the given HTTP status code. In addition to this simple assertion, Laravel also contains a variety of assertions for inspecting the response headers, content, JSON structure, and more.
If you showed your mum/dad/uncle those, the assertGreaterThan
is far more intuitive. Plus the failed message for the isGreaterThan will be much better
"1 was not greater than 2"
or
"false was not true"
Which one is more expressive?
Actually, the best method provides better readability and better failure messages: use the PHPUnit function-based assertions or 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 assertion by adding a string as the first parameter to the assertion methods or Hamcrest's assertThat
function or the third parameter to PHPUnit's 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With