Hamcrest framework was first introduced in Java world, later implemented in other languages (ex. PHP, Python, Ruby) with some exceptions depending on language scopes. It provides a wide range of matcher objects which make test assertion more meaningful and easier to understand.
I am going to use Hamcrest's PHP implementation.
Here is a starter example.
Installation
Hamcrest-php can be installed using composer
// first thing first, install hamcrest-php and include it, your vendor location may vary.
require __DIR__ . '/vendor/autoload.php';
Quick use case - assertThat
Here is a simple example of assertThat
matcher.
$result = true;
$expected = true;
assertThat($result, equalTo($expected));
Give a nice optional description
You can give it a nice description about the assertion.
assertThat("Result should be true", $result, equalTo($expected));
Add a decorator/sugar - is
Hamcrest also provides is
decorator/sugar to make it super declarative!
assertThat("Result should be true", $result, is(equalTo($expected)));
Asserting negation - not
Sometimes we need to test negativity, hamcrest cover this with not
matcher.
$expected = true;
assertThat("Result should not be false", $result, is(not(equalTo($expected))));
When it fails the assertion it shows error message like this
Hamcrest\AssertionError with message 'Result should be true
Expected: <false>
but: was <true>'
Feel free to checkout other matchers or hamcrest in other supported languages!
Top comments (0)