forked from hamcrest/JavaHamcrest
-
Notifications
You must be signed in to change notification settings - Fork 0
Writing First Test Case
Narendra Pathai edited this page Jul 1, 2018
·
1 revision
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));
- Introduction
- Framework Compatibility
- Getting Started
- Matchers
- Core
- Logical
- Object
- Beans
- Collections
- Number
- Text
- Test Readability with "Sugar"
- Writing Custom Matchers
- Sugar Generation
- Third Party Extensions
- Further Resources