I am trying to match two different properties of an Object by org.hamcrest.Matchers. Here it is:
List<LeaveApply> leaveApplyList = Lambda.select(
allLeaveApplyList,
Matchers.allOf(
Lambda.having(
Lambda.on(LeaveApply.class).getUser().getId(),
Matchers.equalTo(userId)),
Lambda.having(
Lambda.on(LeaveApply.class).getDate(),
Matchers.allOf(
Matchers.greaterThanOrEqualTo(fromDate),
Matchers.lessThanOrEqualTo(toDate)))
)
);
It gives a List of LeaveApply Object having user-id equals to given id and date less than or equals to to-date and greater than or equals to from-date. It is working. I want to know is it the right way to match different property fields?
1.1. Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.
It creates a matcher of String that matches when the examined string is equal to the specified expectedString, ignoring case. The following code snippet shows how to use the Hamcrest matcher. It shows that the given list or array hasSize(5) contains five items.
Hamcrest is a framework that assists writing software tests in the Java programming language. It supports creating customized assertion matchers ('Hamcrest' is an anagram of 'matchers'), allowing match rules to be defined declaratively. These matchers have uses in unit testing frameworks such as JUnit and jMock.
A matcher that checks if the given objects are equal. Tests whether the given object is null or not null. Tests if the given object is the exact same instance as another. Actually, all of the above are static methods which take different parameters, and return a Matcher .
It should work, as far as I see. You can do two improvements: use static imports to make it more readable and use having(...).and(...)
instead of using allOf
:
import static ch.lambdaj.Lambda.*;
import static org.hamcrest.Matchers.*;
List<LeaveApply> leaveApplyList = select(allLeaveApplyList, having(on(LeaveApply.class).getUser().getId(), equalTo(userId)).and(on(LeaveApply.class).getDate(), allOf(greaterThanOrEqualTo(fromDate), lessThanOrEqualTo(toDate)))));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With