Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP


grahamrhay edited this page · 14 revisions



"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. This tutorial shows you how to use Hamcrest for unit testing.

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." -

This is a C# port of the Java version of Hamcrest.

Getting Started

Hamcrest matchers provide an alternative to the traditional assertions provided by unit testing frameworks e.g. Assert.AreEqual

    public void This_is_a_test()
        var aBiscuit = new Biscuit("Ginger");
        var anotherBiscuit = new Biscuit("Ginger");
        Assert.That(aBiscuit, Is.EqualTo(myBiscuit));


The only requirement for a matcher is that it implements IMatcher:

    public void Using_matchers()
        var aBiscuit = new Biscuit("Chocolate");
        var matcher = new BiscuitMatcher("Chocolate") // BiscuitMatcher : Matcher<Biscuit>
        var description = new StringDescription();
        Console.WriteLine(description); // Outputs: "Chocolate"

        var matches = matcher.Matches(aBiscuit);
        Console.WriteLine(matches); // Outputs: "true"

        var anotherBiscuit = new Biscuit("Ginger");
        matches = matcher.Matches(anotherBiscuit);
        Console.WriteLine(matches); // Outputs: "false"

        var mismatchDescription = new StringDescription();
        matcher.DescribeMismatch(anotherBiscuit, mismatchDescription);
        Console.WriteLine(mismatchDescription); // Outputs: "was Ginger"

Provided Matchers

Writing your own Matchers

Writing your own matcher is as simple as implementing IMatcher<T>, however there are some building blocks available:


Me, mostly. Pull requests will be warmly received though! Thanks to Igor Brejc ( for the LessThan/GreaterThan matchers.

Something went wrong with that request. Please try again.