Now, there could arise a situation, where we need to have a matcher, which clubs different matchers, kind of like a Composite Matcher.
The idea is not clear right, lets traverse the code.......
public class CompositeMatcher extends BaseMatcher{
static List matcherAndList = new ArrayList();
static List failedMatcherList = new ArrayList();
public CompositeMatcher and(final Matcher matcher)
{
matcherAndList.add(matcher);
return this;
}
public CompositeMatcher(final Matcher matcher)
{
matcherAndList.add(matcher);
}
@Override
public void describeTo(final Description description) {
description.appendText("expected result from CompositeMatcher(): ")
.appendValue(description);
}
@Override
public boolean matches(final Object item) {
System.out.println(" ***** Matcher List is:"+matcherAndList+"\n Size()"+matcherAndList.size());
System.out.println(" ***** The item to be matches is:"+item);
for(Matcher matcher : matcherAndList)
{
if(! matcher.matches(item))
return false;
}
return true;
}
@Override
public void describeMismatch(final Object item,
final Description mismatchDescription) {
mismatchDescription.appendText("was ").appendValue(
item);
}
public static CompositeMatcher all(Matcher matcher)
{
return new CompositeMatcher(matcher);
}
}
and its usage will be:
assertThat(person1, all(hasName("Subha")).and(hasAddress("KOLKATA")));
Where person1 is of type Person.
Now, the matcher we could see here is:
1)hasName
2)hasAddress
3)all
4)and
We are already acquainted with hasName and hasAddress matcher.
Lets go for all & and matchers
If we see the definition of all in CompositeMatcher.java, we could see that it returns a new Object of type CompositeMatcher (taking the matcher as its parameter) and the constructor stores the matcher in the List.
Similarly for and matcher takes a matcher as parameter, stores that matcher in the List and returns the current Object.
The interesting thing to notice here is that, all the matchers are being stored in some DataStructure so that they could be invoked later and return type being CustomMatcher which extends org.hamcrest.BaseMatcher so that if we need another matcher we could do so by using:
assertThat(person1, all(hasName("Subha")).and(hasAddress("KOLKATA")).add(<<put another Matcher here>>));
by this way we can extend the chain. All the matchers are being stored in a Class Level List.
When the above assertThat is executed, then matches() of the CompositeMatcher.java gets called, and it does the MAGIC.....
So, this is in short an introduction to Hamcrest. Any suggestions or opinions are always welcome.
Please share your views.
No comments:
Post a Comment