Getting Started with Hamcrest

Sebastian Bergmann » 08 January 2008 » in Articles, Articles » 6 Comments

I recently started porting Hamcrest to PHP. This tutorial shows you how to use Hamcrest for unit testing with PHP.

Introduction

Hamcrest is a framework for writing matcher objects, allowing match rules to be defined declaratively. There are a number of situations where matchers are invaluble, such as UI validation, or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used.

When writing tests, it is sometimes difficult to get the balance right between overspecifying the test (and making it brittle to changes), and not specifying enough (making the test less valuable since it continues to pass even when the thing being tested is broken). Having a tool that allows you to pick out precisely the aspect under test and describe the values it should have, to a controlled level of precision, helps greatly in writing tests that are "just right". Such tests fail when the behaviour of the aspect under test deviates from the expected behaviour, yet continue to pass when minor, unrelated changes to the behaviour are made.

My first Hamcrest test

We'll start by writing a very simple PHPUnit test, but instead of using PHPUnit's assertEquals() or assertThat() methods, we use Hamcrest's assertThat() function and its standard set of matchers:

<?php
require_once 'PHPUnit/Framework.php';
require_once 'Hamcrest.php';
 
class BiscuitTest extends PHPUnit_Framework_TestCase
{
    public function testEquals()
    {
        $theBiscuit = new Biscuit('Ginger');
        $myBiscuit = new Biscuit('Ginger');
        assertThat($theBiscuit, equalTo($myBiscuit));
    }
}
?>

The assertThat() method is a stylized sentence for making a test assertion. In this example, the subject of the assertion is the object biscuit that is the first method parameter. The second method parameter is a matcher for Biscuit objects, here a matcher that checks one object is equal to another.

If you have more than one assertion in your test you can include an identifier for the tested value in the assertion:

  • assertThat('chocolate chips', $theBiscuit->getChocolateChipCount(), equalTo(10));
  • assertThat('hazelnuts', $theBiscuit->getHazelnutCount(), equalTo(3));

Sugar

Hamcrest strives to make your tests as readable as possible. For example, the is() matcher is a wrapper that doesn't add any extra behavior to the underlying matcher. The following assertions are all equivalent:

  • assertThat($theBiscuit, equalTo($myBiscuit));
  • assertThat($theBiscuit, is(equalTo($myBiscuit)));
  • assertThat($theBiscuit, is($myBiscuit));

A tour of common matchers

Hamcrest comes with a library of useful matchers. Here are the ones that are already ported to PHP:

  • Core
    • anything() - always matches, useful if you don't care what the object under test is
    • describedAs() - decorator to adding custom failure description
    • is() - decorator to improve readability - see "Sugar", above
  • Logical
    • allOf() - matches if all matchers match, short circuits (like PHP &&)
    • anyOf() - matches if any matchers match, short circuits (like PHP ||)
    • not() - matches if the wrapped matcher doesn't match and vice versa
  • Object
    • equalTo() - test object equality using ==
    • anInstanceOf() - test type
    • notNullValue(), nullValue() - test for null
    • sameInstance() - test object identity using ===
  • Number
    • closeTo() - test floating point values are close to a given value
    • greaterThan(), greaterThanOrEqualTo(), lessThan(), lessThanOrEqualTo() - test ordering
  • Text
    • equalToIgnoringCase() - test string equality ignoring case
    • equalToIgnoringWhiteSpace() - test string equality ignoring differences in runs of whitespace
    • containsString(), endsWith(), startsWith() - test string matching

Other test frameworks

Hamcrest has been designed from the outset to integrate with different unit testing frameworks. For example, the Java port of Hamcrest can be used with JUnit 3 and 4 as well as TestNG. It is easy enough to migrate to using Hamcrest-style assertions in an existing test suite, since other assertion styles can co-exist with Hamcrest's.

Hamcrest can also be used with mock objects frameworks by using adaptors to bridge from the mock objects framework's concept of a matcher to a Hamcrest matcher. For example, JMock 1's constraints are Hamcrest's matchers. Hamcrest provides a JMock 1 adaptor to allow you to use Hamcrest matchers in your JMock 1 tests. JMock 2 doesn't need such an adaptor layer since it is designed to use Hamcrest as its matching library. Hamcrest also provides adaptors for EasyMock 2.

Defined tags for this entry: , , ,

Trackback specific URI for this entry

6 Comments to "Getting Started with Hamcrest"

Display comments as (Linear | Threaded)
  1. Travis Swicegood
    09/01/2008 at 15:19 Permalink
    This looks similar to PHPT_Ensure for the PHPT package. The only real difference is that I adopted fluent-API instead of using a more procedural style API and I adopted the name "ensure" instead of "assertThat".

    This is definitely interesting. One thing I noticed though was that there doesn't appear to be any test cases for the code in SVN...?

    Reply

  2. Sebastian Bergmann
    09/01/2008 at 15:36 Permalink
    The tests are there (in the Hamcrest/Tests directory).

    The work on the Hamcrest port for PHP (and its tests especially) is far from complete. The functionality shown in the tutorial, however, works already.

    Reply

  3. Chris Corbyn
    23/03/2009 at 06:17 Permalink
    Hi Sebastian,

    I'm just wondering, did you ever finish working on hamcrest-php? I'd like to use it if you have a link to a finished version somewhere? :) Google Code has some cached copies that are viewable in the web interface, but the hamcrest-php directory does not exist in svn so I assume it was abandoned?

    I'm looking to use it outside of the scope of PHPUnit at this time.

    Cheers,

    Chris

    Reply

  4. Sebastian Bergmann
    23/03/2009 at 06:21 Permalink
    I wanted to start hamcrest-php from scratch some time ago and deleted the directory. I think I will just resurrect it and go from there.

    Reply

  5. Chris Corbyn
    23/03/2009 at 10:38 Permalink
    Hi Sebastian,

    I watched a presentation online that suggested it was PHP 5.3 only. However, this snapshot looks more like 5.2. I'm in need of matchers for 5.2 really. Currently I've got custom non-standard matchers but having something like Hamcrest would improve things a little.

    I guess I'll check out the revision at which this actually existed and go from there.

    Was there anything that was not working correctly or that needed finishing? It's not too important that the entire project is 100% complete for me, provided that the interface names and class names etc will not change.

    Would you consider reviving it and working on it (or allowing me to work on it)?

    Cheers,

    Chris

    Reply

  6. Chris Corbyn
    24/03/2009 at 04:51 Permalink
    Last night I began porting Hamcrest for PHP 5.2. Namespaces do make things a bit more elegant but they just don't exist in a stable PHP build yet. I'm considering making this available as hamcrest-php5.2 or something.

    The alternative is to have both the 5.2 (and probably working with 5.1) and the 5.3 versions transparently hidden within hamcrest-php. So you can use class names like Hamcrest_Matcher, or you can use Hamcrest::Matcher.

    Unfortunately the two can't easily inter-operate I don't think though (i.e. you can use a mix of non-namespaced interfaces and namespaced ones).

    Reply

0 Trackbacks to "Getting Started with Hamcrest"

  1. No Trackbacks

Add Comment


To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Submitted comments will be subject to moderation before being displayed.