Giriş
Açıklaması şöyle
Hamcrest is an assertion library that helps to build a declarative pipeline of matchers.
assertThat
Şu satırı dahil ederiz
import static org.hamcrest.MatcherAssert.assertThat;
Daha sonra hazır gelen Matchers.XX metodları ile kullanırız
Collection Matcher
empty(), hasSize(), arrayWithSize(),containsInAnyOrder(),contains(),hasItemInArray(),isOneOf(),isIn(),arrayContainingInAnyOrder(), arrayContaining(),hasKey(),hasValue(),hasEntry()
gibi bir sürü metod var
hasSize
Şu satırı dahil ederiz
import static static org.hamcrest.collection.IsCollectionWithSize.hasSize;
Örnek
Şöyle yaparız
assertThat(res, hasSize(3));
TypeSafeMatcher
matchesSafely() ve describeTo() metodlarını override etmek yeterli.
Örnek
Şöyle yaparız
Matcher<List<PostView>> hasComments(int count) {
return new TypeSafeMatcher<>() {
@Override
protected boolean matchesSafely(List<PostView> item) {
return item.stream()
.allMatch(post -> post.comments().size() == count);
}
@Override
public void describeTo(Description description) {
description.appendText(count + " comments in each post");
}
@Override
protected void describeMismatchSafely(List<PostView> item,
Description mismatchDescription) {
mismatchDescription.appendText(
item.stream()
.map(postView -> format(
"PostView[%d] with %d comments",
postView.id(),
postView.comments().size()
))
.collect(joining(" ; "))
);
}
};
}