Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are specific asserts better than generic asserts, in PHPUnit?

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!

like image 953
Spot Avatar asked Oct 25 '12 18:10

Spot


People also ask

What is assert in PHPUnit?

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.

How do I assert exceptions in PHPUnit?

phpunit Assertions Assert an Exception is ThrownexpectException($exception) expectExceptionMessage($message) expectExceptionCode($code)

Can you have multiple asserts?

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.

What is assertion in laravel?

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.


2 Answers

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?

like image 158
Martin Lyne Avatar answered Sep 21 '22 17:09

Martin Lyne


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
like image 29
David Harkness Avatar answered Sep 19 '22 17:09

David Harkness