Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.hamcrest.Matchers for matching different properties simultaneously of an Object

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?

like image 898
Tapas Bose Avatar asked Apr 15 '11 04:04

Tapas Bose


People also ask

What is org hamcrest matchers in?

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.

How do you use hamcrest matchers?

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.

What is a hamcrest matcher?

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.

What are matchers in testing?

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 .


1 Answers

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)))));
like image 173
Joachim Sauer Avatar answered Oct 04 '22 23:10

Joachim Sauer