是否可以根据条目的一组条件对整个集合进行断言。 让我们有一份员工名单。
List<Employee>
我的测试用例需要验证列表中的所有值是否满足其中一个条件:
If age > 60 then status == Status.Retired
If age < 18 then status == Status.Student
正在尝试探索是否可以使用 foreach
和 lambda:
Consumer<Employee> lambdaExpression = x ->
(x.getAge() < 18 && x.getStatus == Status.Student) ||
(x.getAge() > 60 && x.getStatus == Status.Retired)||
(x.getAge() > 18 && x.getAge() < 60
&& x.getStatus==Status.Employed);
assertTrue(params.forEach((n) -> lambdaExpression));
这在某种程度上是可能的吗?
最佳答案
您可以使用流和 allMatch
:
Predicate<Employee> predicate =
emp -> (emp.getAge() <= 60 && emp.getAge() >= 18
&& Status.Employed == emp.getStatus())
|| (emp.getAge() > 60 && Status.Retired == emp.getStatus())
|| (emp.getAge() < 18 && Status.Student == emp.getStatus())
assertTrue(params.stream().allMatch(predicate));
关于java - 单次通过条目集合的断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743033/