使用 AssertJ 断言列表中的单个对象
Asserting individual Objects in List using AssertJ
我正在使用 AssertJ 库在我的测试中执行断言。在这种情况下,我想测试列表中的每个 Date
对象是否都在其他日期之后。
所以我显然可以做到以下几点:
Date dateOne = new Date(someTimestamp);
Date dateTwo = new Date(otherTimestamp);
Assertions.assertThat(dateOne).isAfter(dateTwo);
没有问题。
但是如果我想测试列表的每个元素以确保它们都在给定日期之后怎么办。
Date dateOne = new Date(someTimestamp);
Date dateTwo = new Date(otherTimestamp);
Date dateThree = new Date(fooBarTimestamp);
List<Date> dates = Arrays.asList(dateOne, dateTwo);
//and here I want to make sure that all Dates in dates are after dateThree
我通过创建自定义 org.assertj.core.api.Condition
来管理它并使用了这个语法:
Assertions.assertThat(dates).is(allAfterDate(dateThree));
但是比较器看起来非常整洁,最重要的是,我的 SonarQube 抱怨这个签名:
Condition<List<? extends Date>> allAfterDate(final Date dateToCompare) {...}
违反了Generic wildcard types should not be used in return parameters规则。如果我不确定这是我这次可以打破的规则,我倾向于相信 SonarQube。我不确定。
我喜欢使用 SoftAssertions
,因此解决方法是使用:
SoftAssertions assertions = new SoftAssertions();
dates.forEach( date -> {
assertions.assertThat(date).isAfter(dateThree);
});
assertions.assertAll();
但我觉得这应该可以使用大多数开发人员非常喜欢的这种很酷的 AssertJ 语法;-)
有什么方法可以做类似的事情吗?
Assertions.assertThat(dates).everySingleElement().isAfter(dateThree);
如果这是不可能的,最好和最干净的方法是什么?
(我知道我可以用 //NOSONAR
抑制声纳,我只是不想)
尝试 allSatisfy
:
assertThat(dates).allSatisfy(date -> assertThat(date).isAfter(dateThree));
希望它对您有所帮助,并且是一个足够酷的语法;-)
我正在使用 AssertJ 库在我的测试中执行断言。在这种情况下,我想测试列表中的每个 Date
对象是否都在其他日期之后。
所以我显然可以做到以下几点:
Date dateOne = new Date(someTimestamp);
Date dateTwo = new Date(otherTimestamp);
Assertions.assertThat(dateOne).isAfter(dateTwo);
没有问题。
但是如果我想测试列表的每个元素以确保它们都在给定日期之后怎么办。
Date dateOne = new Date(someTimestamp);
Date dateTwo = new Date(otherTimestamp);
Date dateThree = new Date(fooBarTimestamp);
List<Date> dates = Arrays.asList(dateOne, dateTwo);
//and here I want to make sure that all Dates in dates are after dateThree
我通过创建自定义 org.assertj.core.api.Condition
来管理它并使用了这个语法:
Assertions.assertThat(dates).is(allAfterDate(dateThree));
但是比较器看起来非常整洁,最重要的是,我的 SonarQube 抱怨这个签名:
Condition<List<? extends Date>> allAfterDate(final Date dateToCompare) {...}
违反了Generic wildcard types should not be used in return parameters规则。如果我不确定这是我这次可以打破的规则,我倾向于相信 SonarQube。我不确定。
我喜欢使用 SoftAssertions
,因此解决方法是使用:
SoftAssertions assertions = new SoftAssertions();
dates.forEach( date -> {
assertions.assertThat(date).isAfter(dateThree);
});
assertions.assertAll();
但我觉得这应该可以使用大多数开发人员非常喜欢的这种很酷的 AssertJ 语法;-)
有什么方法可以做类似的事情吗?
Assertions.assertThat(dates).everySingleElement().isAfter(dateThree);
如果这是不可能的,最好和最干净的方法是什么?
(我知道我可以用 //NOSONAR
抑制声纳,我只是不想)
尝试 allSatisfy
:
assertThat(dates).allSatisfy(date -> assertThat(date).isAfter(dateThree));
希望它对您有所帮助,并且是一个足够酷的语法;-)