我试图验证提取的列表中的第一项。但AssertJ从List
返回.first()
而不是预期的对象。
给出以下示例
public class AssertJTests
{
@Test
@DisplayName("Region Asia should only have one Country, Malaysia")
public void assertRegion()
{
Region asia = new Region()
.setName("Asia")
.setCountries(Lists.newArrayList("Malaysia"));
Consumer<Region> regionRequirement = region ->
assertThat(region)
.extracting(Region::getName)
.containsOnly("Asia");
Consumer<String> countryRequirement = country ->
assertThat(country)
.isEqualToIgnoringCase("Malaysia");
assertThat(asia)
.isInstanceOfSatisfying(Region.class, regionRequirement)
.extracting(Region::getCountries)
.hasSize(1)
.first()
.isInstanceOfSatisfying(String.class, countryRequirement);
}
protected static class Region
{
private String name;
private List<String> countries;
List<String> getCountries()
{
return countries;
}
Region setCountries(final List<String> pCountries)
{
countries = pCountries;
return this;
}
String getName()
{
return name;
}
Region setName(final String pName)
{
name = pName;
return this;
}
}
}
我希望.first()
返回String
,而是返回List<String>
。出现以下错误:
java.lang.AssertionError:[List check first element] 期待: 百分比抑制率&#34;马来西亚&#34;&GT; 成为: &LT; java.lang.String中&GT; 但是的例子是: &LT; java.util.ArrayList中&GT;
答案 0 :(得分:1)
Object
断言, extracting
提取受测试对象(此处为asia
)属性,从而生成List
提取的属性值。您的代码导致只提取一个属性,因此结果是一个值的列表,结果是该值也是一个列表,在extracting
之后,您最终得到的是一个元素的List
asia.countries
。
答案 1 :(得分:0)
您可以使用API的contains
和extracting
方法进行断言。
例如:
@Test
public void oneDateShouldNotAfterAnotherDate() {
Set<String> errors = ...;
Assertions
.assertThat(errors)
.isNotEmpty()
.contains("OneDate_ShouldNot_After_AnotherDate");
/*
If you need assert specific field of object. Then:
*/
Set<Error> errors = ...;
Assertions
.assertThat(errors)
.isNotEmpty()
.extracting("message")
.contains("OneDate_ShouldNot_After_AnotherDate");
}