Skip to main content

Testing Toolbelt: Hamcrest Matchers

The Hamcrest Matchers framework contains a series of Matcher classes which help implement comparison and assertion methods in a type-safe, declarative manner. When used in tests, the Matchers framework will produce more legible test code and more helpful failure messages. The Matchers framework is partially included in the JUnit 4.4 package and some portions can be used effectively. But, the full power of the framework can only be unleashed by including the real Hamcrest Matchers jar within your testing environment.

Matchers

The org.hamcrest.Matchers class in the Hamcrest framework provides a series of methods, intended to be used with import static, which supply various pre-defined org.hamcrest.core.Matcher instances.

  • is -- The simplest matcher, most times behaves just as syntactical sugar around other matchers. But, if an instance of Class is passed, it behaves like the Matcher produced by instanceOf. If passed any other value, behaves like the Matcher produced by equalsTo. see org.hamcrest.core.Is
  • equalTo -- Verifies that the test value is equal to the value used to instantiate the Matcher. see org.hamcrest.core.IsEqual
  • instanceOf -- Verifies that the test value is assignable to the Class value used to instantiate the Matcher. see org.hamcrest.core.IsInstanceOf
  • nullValue/nonNullValue -- Verifies that the test value is null-valued/not-null-valued. see org.hamcrest.core.IsNull
  • startsWith/containsString/endsWith -- Verifies that the test value (String\-typed) begins with, contains, or ends with the value used to instatiate the Matcher. see org.hamcrest.core.StringStartsWith, org.hamcrest.core.StringContains, and org.hamcrest.core.StringEndsWith
  • arrayWithSize/emptyArray/hasSize/empty -- Verifies that the test value is an array/collection that either has the given number of elements/is empty. see org.hamcrest.core.IsArrayWithSize, org.hamcrest.core.IsCollectionWithSize, and org.hamcrest.core.IsEmptyCollection
  • lessThan/lessThanOrEqualTo/greaterThanOrEqualTo/greaterThan -- Verifies that the test value is strictly less than/less than/greater than/strictly greater than the provided value. see org.hamcrest.core.OrderingComparison

Examples

public class MatcherSample {

  @Test public void matcherSample() {
    // doesn't compile, type-safety in action
    // assertThat(1, is("VALUE"));

    // is, with a Class-typed operand...
    assertThat("VALUE", is(String.class));
    // ...is resolved to this...
    assertThat("VALUE", is(instanceOf(String.class)));
    // ...which is then unwrapped to this
    assertThat("VALUE", instanceOf(String.class));

    // is, with a reference-type operand...
    assertThat("VALUE", is("VALUE"));
    // ...is resolved to this...
    assertThat("VALUE", is(equalTo("VALUE")));
    // ... which is then unwrapped to this
    assertThat("VALUE", equalTo("VALUE"));

    // is, with a primitive value
    assertThat(1, is(1));

    // assert null-valued
    assertThat(null, is(nullValue()));
    // assert null-valued, checking type
    assertThat((String) null, is(nullValue(String.class)));
    // assert non-null
    assertThat("VALUE", is(notNullValue()));

    // Matchers for Strings
    // you could use is() with these, but is more readable without
    assertThat("VALUABLE", startsWith("VALU"));
    assertThat("VALUABLE", containsString("LUA"));
    assertThat("VALUABLE", endsWith("ABLE"));

    // Matchers for Arrays and Collections
    final String[] strings1 = {};
    assertThat(strings1, is(emptyArray()));
    assertThat(strings1, is(arrayWithSize(0)));
    assertThat(Arrays.asList(strings1), hasSize(0));
    final String[] strings2 = { "VALUE_1", "VALUE_2" };
    assertThat(strings2, is(arrayWithSize(2)));
    assertThat(strings2, is(arrayContaining("VALUE_1", "VALUE_2")));
    assertThat(Arrays.asList(strings2), hasSize(2));
    assertThat(Arrays.asList(strings2), contains("VALUE_1", "VALUE_2"));

    // Matchers for Numerics
    assertThat(1, is(lessThan(10)));
    assertThat(1, is(greaterThan(0)));
    assertThat(1, is(lessThanOrEqualTo(1)));
    assertThat(1, is(greaterThanOrEqualTo(1)));

    // use both/allOf/either/anyOf for composition of matchers
    // both/allOf is equivalent to and'ing the Matchers
    assertThat(1, is(both(greaterThan(0)).and(lessThan(10))));
    assertThat(1, is(allOf(greaterThan(0), lessThan(10))));
    // either/anyOf is equivalent to or'ing the Matchers
    assertThat(100, is(either(lessThan(0)).or(greaterThan(10))));
    assertThat(100, is(anyOf(lessThan(0), greaterThan(10))));
  }
}

Comments

Popular posts from this blog

Using MonoDevelop to Create an ASP.NET Web Service

NOTE: instructions below are for MonoDevelop 2.6 Beta 2 - built on 2011-04-06 03:37:58+0000Getting StartedCreate a new ASP.NET Web Application in MonoDevelop: From the menu, select: File → New → Solution…Expand C#.Select ASP.NET → Web Application.Enter a name for the ASP.NET project that will be created in the solution in Name:.Change the root location for the solution in Location:, if desired.Change the name of the root solution in Solution Name:, if desired.The Results – IWhat you have after executing the new ASP.NET Web Application project wizard is a solution containing one ASP.NET Web Application project. In the default project view in MonoDevelop, you'll find the following items: Default.aspx – This is the default web form rendered and presented in the browser when http://<server>:<port>/ is accessed. Default.aspx.cs – This C# file contains the developer-created common code and event handlers which can be used to affect the processing of the form.Default.aspx.des…

Testing Toolbelt: SpringJUnit4ClassRunner

The org.springframework.test.context.junit4.SpringJUnit4ClassRunner class is another implementation of the JUnit TestRunner class which is used to enable various features of Spring for every run of the test class and every test within it. To use the features provided by the SpringJUnit4ClassRunner class, you need to mark the class using the RunWith annotation using SpringJUnit4ClassRunner as its parameter.In addition to the custom test runner, you will want to mark the class with the ContextConfiguration annotation. The ContextConfiguration annotation is used to mark classes which will automatically read a Spring configuration file and use it to create an ApplicationContext. By default, this file located at <package path>/<test class name>-context.xml. Use the locations argument to over-ride.The ApplicationContext used by the Spring-integrated test will only be loaded once for the whole test class. This behavior can be over-ridden by annotating a test method with the Dirti…