Writing First Test Case - npathai/JavaHamcrest GitHub Wiki

We'll start by writing a very simple JUnit test, but instead of using JUnit's assertEquals methods, we use Hamcrest's assertThat construct and the standard set of matchers, both of which we statically import:

import static org.hamcrest.MatcherAssert.assertThat; 
import static org.hamcrest.Matchers.*;

import junit.framework.TestCase;

public class BiscuitTest { 
  
  @Test
  public void testEquals() { 
    Biscuit theBiscuit = new Biscuit("Ginger"); 
    Biscuit 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 using the Object equals method. The test passes since the Biscuit class defines an equals method.

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));