I'm trying to verify first item in an extracted List. However AssertJ returns a List
instead of expected object from .first()
.
Given the following sample
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;
}
}
}
I'm expecting .first()
to return String
but instead it returned List<String>
. The following error appeared:
java.lang.AssertionError: [List check first element] Expecting: <["Malaysia"]> to be an instance of: <java.lang.String> but was instance of: <java.util.ArrayList>
extracting
for Object
assertion extracts the object under test (here asia
) properties resulting in a List
of extracted property values. Your code results in extracting only one property so the result is a list of one value, it turns out that the value is also a list, after extracting
you end up having is a List
of one element being asia.countries
.