DEV Community

Shaikhul Islam
Shaikhul Islam

Posted on

1

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs