- Objects:
equalTo, hasToString, instanceOf, isCompatibleType, notNullValue, nullValue, sameInstance
- Textual content:
equalToIgnoringCase, equalToIgnoringWhiteSpace, containsString, endsWith, startsWith
- Numbers:
closeTo, greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo
- Logical:
allOf, anyOf, not
- Collections:
array
(evaluate an array to an array of matchers),hasEntry, hasKey, hasValue, hasItem, hasItems, hasItemInArray
The next code pattern reveals a couple of examples of utilizing Hamcrest in a JUnit 5 check class.
Itemizing 1. Utilizing Hamcrest in a JUnit 5 check class (HamcrestDemoTest.java)
bundle com.javaworld.geekcap.hamcrest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Take a look at;
import java.util.ArrayList;
import java.util.Checklist;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
class HamcrestDemoTest {
@Take a look at
@DisplayName("String Examples")
void stringExamples() {
String s1 = "Hey";
String s2 = "Hey";
assertThat("Evaluating Strings", s1, is(s2));
assertThat(s1, equalTo(s2));
assertThat("ABCDE", containsString("BC"));
assertThat("ABCDE", not(containsString("EF")));
}
@Take a look at
@DisplayName("Checklist Examples")
void listExamples() {
// Create an empty record
Checklist record = new ArrayList();
assertThat(record, isA(Checklist.class));
assertThat(record, empty());
// Add a pair gadgets
record.add("One");
record.add("Two");
assertThat(record, not(empty()));
assertThat(record, hasSize(2));
assertThat(record, incorporates("One", "Two"));
assertThat(record, containsInAnyOrder("Two", "One"));
assertThat(record, hasItem("Two"));
}
@Take a look at
@DisplayName("Quantity Examples")
void numberExamples() {
assertThat(5, lessThan(10));
assertThat(5, lessThanOrEqualTo(5));
assertThat(5.01, closeTo(5.0, 0.01));
}
}
One factor I like about Hamcrest is that it is vitally simple to learn. For instance, “assert that identify is Steve
,” “assert that record has dimension 2
,” and “assert that record has merchandise Two
” all learn like common sentences within the English language. In Itemizing 1, the stringExamples
check first compares two String
s for equality after which checks for substrings utilizing the containsString()
methodology. An optionally available first argument to assertThat()
is the “cause” for the check, which is identical because the message in a JUnit assertion and shall be displayed if the check fails. For instance, if we added the next check, we’d see the assertion error under it:
assertThat("Evaluating Strings", s1, is("Goodbye"));
java.lang.AssertionError: Evaluating Strings
Anticipated: is "Goodbye"
however: was "Hey"
Additionally be aware that we will mix the not()
logical methodology with a situation to confirm {that a} situation shouldn’t be true. In Itemizing 1, we verify that the ABCDE String
doesn’t comprise substring EF
utilizing the not()
methodology mixed with containsString()
.