DEV Community

Shaikhul Islam
Shaikhul Islam

Posted on

Hamcrest - make your test assertion more declarative

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';
Enter fullscreen mode Exit fullscreen mode

Quick use case - assertThat

Here is a simple example of assertThat matcher.

$result = true;
$expected = true;

assertThat($result, equalTo($expected));
Enter fullscreen mode Exit fullscreen mode

Give a nice optional description

You can give it a nice description about the assertion.

assertThat("Result should be true", $result, equalTo($expected));
Enter fullscreen mode Exit fullscreen mode

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)));
Enter fullscreen mode Exit fullscreen mode

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))));
Enter fullscreen mode Exit fullscreen mode

When it fails the assertion it shows error message like this

Hamcrest\AssertionError with message 'Result should be true
Expected: <false>
     but: was <true>'
Enter fullscreen mode Exit fullscreen mode

Feel free to checkout other matchers or hamcrest in other supported languages!

Top comments (0)