org.hamcrest.Matchers用于同时匹配Object的不同属性

时间:2011-04-15 04:39:18

标签: java hamcrest lambdaj

我试图通过org.hamcrest.Matchers匹配Object的两个不同属性。这是:

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)))
                 )
              );

它给出一个LeaveApply对象列表,其中user-id等于给定的id和日期小于或等于to-date且大于或等于from-date。这是工作。我想知道它是匹配不同属性字段的正确方法吗?

1 个答案:

答案 0 :(得分:7)

据我所知,它应该可行。您可以做两项改进:使用静态导入使其更具可读性并使用having(...).and(...)而不是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)))));