SELF - the "self" type of this assertion class. Please read "Emulating 'self types' using Java Generics to simplify fluent API implementation"
for more details.ACTUAL - the type of the "actual" value.ELEMENT - the type of elements of the "actual" value.ELEMENT_ASSERT - used for navigational assertions to return the right assert type.public abstract class AbstractIterableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> extends AbstractAssert<SELF,ACTUAL> implements ObjectEnumerableAssert<SELF,ELEMENT>
ObjectEnumerableAssert whose actual value type is
Collection.| Modifier and Type | Field and Description |
|---|---|
protected Iterables |
iterables |
actual, info, myself, objects, throwUnsupportedExceptionOnEquals| Modifier | Constructor and Description |
|---|---|
protected |
AbstractIterableAssert(ACTUAL actual,
Class<?> selfType) |
| Modifier and Type | Method and Description |
|---|---|
SELF |
allMatch(Predicate<? super ELEMENT> predicate)
Verifies that all the elements of actual match the given
Predicate. |
SELF |
allMatch(Predicate<? super ELEMENT> predicate,
String predicateDescription)
Verifies that all the elements of actual match the given
Predicate. |
SELF |
allSatisfy(Consumer<? super ELEMENT> requirements)
Verifies that all the elements satisfy the given requirements expressed as a
Consumer. |
SELF |
allSatisfy(ThrowingConsumer<? super ELEMENT> requirements)
Verifies that all the elements satisfy the given requirements expressed as a
ThrowingConsumer. |
SELF |
anyMatch(Predicate<? super ELEMENT> predicate)
Verifies whether any elements match the provided
Predicate. |
SELF |
anySatisfy(Consumer<? super ELEMENT> requirements)
Verifies that at least one element satisfies the given requirements expressed as a
Consumer. |
SELF |
anySatisfy(ThrowingConsumer<? super ELEMENT> requirements)
Verifies that at least one element satisfies the given requirements expressed as a
ThrowingConsumer. |
SELF |
are(Condition<? super ELEMENT> condition)
Verifies that each element value satisfies the given condition.
|
SELF |
areAtLeast(int times,
Condition<? super ELEMENT> condition)
Verifies that there are at least n elements in the actual group satisfying the given condition.
|
SELF |
areAtLeastOne(Condition<? super ELEMENT> condition)
Verifies that there is at least one element in the actual group satisfying the given condition.
|
SELF |
areAtMost(int times,
Condition<? super ELEMENT> condition)
Verifies that there are at most n elements in the actual group satisfying the given condition.
|
SELF |
areExactly(int times,
Condition<? super ELEMENT> condition)
Verifies that there are exactly n elements in the actual group satisfying the given condition.
|
SELF |
areNot(Condition<? super ELEMENT> condition)
Verifies that each element value does not satisfy the given condition.
|
SELF |
as(Description description)
Sets the description of the assertion that is going to be called after.
|
SELF |
as(String description,
Object... args)
Sets the description of the assertion that is going to be called after.
|
SELF |
contains(ELEMENT... values)
Verifies that the actual group contains the given values, in any order.
|
SELF |
containsAll(Iterable<? extends ELEMENT> iterable)
Verifies that the actual group contains all the elements of given
Iterable, in any order. |
SELF |
containsAnyElementsOf(Iterable<? extends ELEMENT> iterable)
|
SELF |
containsAnyOf(ELEMENT... values)
Verifies that the actual
Iterable contains at least one of the given values. |
protected SELF |
containsAnyOfForProxy(ELEMENT[] values) |
SELF |
containsExactly(ELEMENT... values)
Verifies that the actual group contains exactly the given values and nothing else, in order.
This assertion should only be used with groups that have a consistent iteration order (i.e. |
SELF |
containsExactlyElementsOf(Iterable<? extends ELEMENT> iterable)
Same as
ObjectEnumerableAssert.containsExactly(Object...) but handle the Iterable to array conversion : verifies that
actual contains exactly the elements of the given iterable and nothing else in the same order. |
protected SELF |
containsExactlyForProxy(ELEMENT[] values) |
SELF |
containsExactlyInAnyOrder(ELEMENT... values)
Verifies that the actual group contains exactly the given values and nothing else, in any order.
|
SELF |
containsExactlyInAnyOrderElementsOf(Iterable<? extends ELEMENT> values)
Verifies that the actual group contains exactly the given values and nothing else, in any order.
|
protected SELF |
containsExactlyInAnyOrderForProxy(ELEMENT[] values) |
protected SELF |
containsForProxy(ELEMENT[] values) |
SELF |
containsNull()
Verifies that the actual group contains at least a null element.
|
SELF |
containsOnly(ELEMENT... values)
Verifies that the actual group contains only the given values and nothing else, in any order and ignoring duplicates (i.e.
|
SELF |
containsOnlyElementsOf(Iterable<? extends ELEMENT> iterable)
Deprecated.
|
protected SELF |
containsOnlyForProxy(ELEMENT[] values) |
SELF |
containsOnlyNulls()
Verifies that the actual group contains only null elements and nothing else.
|
SELF |
containsOnlyOnce(ELEMENT... values)
Verifies that the actual group contains the given values only once.
|
SELF |
containsOnlyOnceElementsOf(Iterable<? extends ELEMENT> iterable)
Same semantic as
ObjectEnumerableAssert.containsOnlyOnce(Object...) : verifies that the actual group contains the elements of
the given iterable only once. |
protected SELF |
containsOnlyOnceForProxy(ELEMENT[] values) |
SELF |
containsSequence(ELEMENT... sequence)
Verifies that the actual group contains the given sequence in the correct order and without extra values between the sequence values.
|
SELF |
containsSequence(Iterable<? extends ELEMENT> sequence)
Verifies that the actual group contains the given sequence in the correct order and without extra values between the sequence values.
|
protected SELF |
containsSequenceForProxy(ELEMENT[] sequence) |
SELF |
containsSubsequence(ELEMENT... subsequence)
Verifies that the actual group contains the given subsequence in the correct order (possibly with other values between them).
|
SELF |
containsSubsequence(Iterable<? extends ELEMENT> subsequence)
Verifies that the actual group contains the given subsequence in the correct order (possibly with other values between them).
|
protected SELF |
containsSubsequenceForProxy(ELEMENT[] subsequence) |
SELF |
describedAs(Description description)
Sets the description of the assertion that is going to be called after.
|
SELF |
describedAs(String description,
Object... args)
Sets the description of the assertion that is going to be called after.
|
SELF |
doesNotContain(ELEMENT... values)
Verifies that the actual group does not contain the given values.
|
SELF |
doesNotContainAnyElementsOf(Iterable<? extends ELEMENT> iterable)
Verifies that actual does not contain any elements of the given
Iterable (i.e. |
protected SELF |
doesNotContainForProxy(ELEMENT[] values) |
SELF |
doesNotContainNull()
Verifies that the actual group does not contain null elements.
|
SELF |
doesNotContainSequence(ELEMENT... sequence)
Verifies that the actual group does not contain the given sequence,
a sequence is defined by an ordered group of values without extra values between them.
|
SELF |
doesNotContainSequence(Iterable<? extends ELEMENT> sequence)
Verifies that the actual group does not contain the given sequence,
a sequence is defined by an ordered group of values without extra values between them.
|
protected SELF |
doesNotContainSequenceForProxy(ELEMENT[] sequence) |
SELF |
doesNotContainSubsequence(ELEMENT... subsequence)
Verifies that the actual group does not contain the given subsequence,
a subsequence is defined by an ordered group of values with possibly extra values between them.
|
SELF |
doesNotContainSubsequence(Iterable<? extends ELEMENT> subsequence)
Verifies that the actual group does not contain the given subsequence,
a subsequence is defined by an ordered group of values with possibly extra values between them.
|
protected SELF |
doesNotContainSubsequenceForProxy(ELEMENT[] subsequence) |
SELF |
doesNotHave(Condition<? super ACTUAL> condition)
Verifies that the actual value does not satisfy the given condition.
|
SELF |
doesNotHaveAnyElementsOfTypes(Class<?>... unexpectedTypes)
Verifies that all elements in the actual
Iterable do not have the specified types (including subclasses). |
SELF |
doesNotHaveDuplicates()
Verifies that the actual group does not contain duplicates.
|
SELF |
doesNotHaveSameClassAs(Object other)
Verifies that the actual value does not have the same class as the given object.
|
SELF |
doNotHave(Condition<? super ELEMENT> condition)
Verifies that all elements do not satisfy the given condition.
|
ELEMENT_ASSERT |
element(int index)
Navigate and allow to perform assertions on the chosen element of the
Iterable under test. |
<ASSERT extends AbstractAssert<?,?>> |
element(int index,
InstanceOfAssertFactory<?,ASSERT> assertFactory)
Navigate and allow to perform assertions on the chosen element of the
Iterable under test. |
SELF |
elements(int... indices)
Allow to perform assertions on the elements corresponding to the given indices
(the iterable
Iterable under test is changed to an iterable with the selected elements). |
SELF |
endsWith(ELEMENT[] sequence)
Verifies that the actual group ends with the given sequence of objects, without any other objects between them.
|
SELF |
endsWith(ELEMENT first,
ELEMENT... rest)
Verifies that the actual group ends with the given sequence of objects, without any other objects between them.
|
protected SELF |
endsWithForProxy(ELEMENT first,
ELEMENT[] rest) |
AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> |
extracting(Function<? super ELEMENT,?>... extractors)
|
<V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> |
extracting(Function<? super ELEMENT,V> extractor)
Extract the values from Iterable's elements under test by applying an extracting function on them.
|
AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> |
extracting(String... propertiesOrFields)
Extract the values of the given fields/properties from the Iterable's elements under test into a new Iterable composed
of Tuples (a simple data structure), this new Iterable becoming the Iterable under test.
|
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
extracting(String propertyOrField)
Extract the values of the given field or property from the Iterable's elements under test into a new Iterable, this new
Iterable becoming the Iterable under test.
|
<P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> |
extracting(String propertyOrField,
Class<P> extractingType)
Extract the values of given field or property from the Iterable's elements under test into a new Iterable, this new
Iterable becoming the Iterable under test.
|
<V,EXCEPTION extends Exception> |
extracting(ThrowingExtractor<? super ELEMENT,V,EXCEPTION> extractor)
Extract the values from Iterable's elements under test by applying an extracting function (which might throw an
exception) on them.
|
protected AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> |
extractingForProxy(Function<? super ELEMENT,?>[] extractors) |
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
extractingResultOf(String method)
Extract the result of given method invocation on the Iterable's elements under test into a new Iterable, this new
Iterable becoming the Iterable under test.
|
<P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> |
extractingResultOf(String method,
Class<P> extractedType)
Extract the result of given method invocation on the Iterable's elements under test into a new list of the given
class, this new List becoming the object under test.
|
SELF |
filteredOn(Condition<? super ELEMENT> condition)
Filters the iterable under test keeping only elements matching the given
Condition. |
<T> SELF |
filteredOn(Function<? super ELEMENT,T> function,
T expectedValue)
Filters the iterable under test keeping only elements for which the result of the
function is equal to expectedValue. |
SELF |
filteredOn(Predicate<? super ELEMENT> predicate)
Filters the iterable under test keeping only elements matching the given
Predicate. |
SELF |
filteredOn(String propertyOrFieldName,
FilterOperator<?> filterOperator)
Filters the iterable under test keeping only elements having a property or field matching the filter expressed with
the
FilterOperator, the property/field is specified by propertyOrFieldName parameter. |
SELF |
filteredOn(String propertyOrFieldName,
Object expectedValue)
Filters the iterable under test keeping only elements having a property or field equal to
expectedValue, the
property/field is specified by propertyOrFieldName parameter. |
SELF |
filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions)
Filters the iterable under test keeping only elements matching the given assertions specified with a
Consumer. |
SELF |
filteredOnAssertions(ThrowingConsumer<? super ELEMENT> elementAssertions)
Filters the iterable under test keeping only elements matching the given assertions specified with a
ThrowingConsumer. |
SELF |
filteredOnNull(String propertyOrFieldName)
Filters the iterable under test keeping only elements whose property or field specified by
propertyOrFieldName is null. |
ELEMENT_ASSERT |
first()
Navigate and allow to perform assertions on the first element of the
Iterable under test. |
<ASSERT extends AbstractAssert<?,?>> |
first(InstanceOfAssertFactory<?,ASSERT> assertFactory)
Navigate and allow to perform assertions on the first element of the
Iterable under test. |
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
flatExtracting(Function<? super ELEMENT,?>... extractors)
Extracts multiple values from each
Iterable's element according to the given Functions and
concatenates/flattens them in a list that becomes the instance under test. |
<V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> |
flatExtracting(Function<? super ELEMENT,? extends Collection<V>> extractor)
Extracts Iterable elements values by applying a function and concatenates the result into a list that becomes the instance
under test.
|
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
flatExtracting(String... fieldOrPropertyNames)
Extract the given property/field values from each
Iterable's element and
flatten the extracted values in a list that is used as the new object under test. |
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
flatExtracting(String fieldOrPropertyName)
Extract Iterable's elements values corresponding to the given property/field name and concatenates them into a list becoming
the new instance under test.
|
<EXCEPTION extends Exception> |
flatExtracting(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>... extractors)
Extracts multiple values from each
Iterable's element according to the given ThrowingExtractors
and concatenates/flattens them in a list that becomes the object under test. |
<V,EXCEPTION extends Exception> |
flatExtracting(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION> extractor)
Extracts Iterable elements values by applying a function (which might throw a checked exception) on them and
concatenates/flattens the result into a single list that becomes the instance under test.
|
protected AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
flatExtractingForProxy(Function<? super ELEMENT,?>[] extractors) |
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
flatMap(Function<? super ELEMENT,?>... mappers)
Maps multiple values from each
Iterable's element according to the given Functions
and concatenates/flattens them in a list that becomes the instance under test. |
<V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> |
flatMap(Function<? super ELEMENT,? extends Collection<V>> mapper)
Maps the Iterable's elements under test by applying the given
Function and flattens the resulting collections in a
list becoming the object under test. |
<EXCEPTION extends Exception> |
flatMap(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>... mappers)
Maps multiple values from each
Iterable's element according to the given ThrowingExtractors and
concatenates/flattens them in a list that becomes the object under test. |
<V,EXCEPTION extends Exception> |
flatMap(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION> mapper)
Maps the Iterable's elements under test by applying a mapping function (which might throw a checked exception) and
concatenates/flattens the result into a single list that becomes the instance under test.
|
protected TypeComparators |
getComparatorsByType() |
protected TypeComparators |
getComparatorsForElementPropertyOrFieldTypes() |
SELF |
has(Condition<? super ACTUAL> condition)
Verifies that the actual value satisfies the given condition.
|
SELF |
hasAtLeastOneElementOfType(Class<?> expectedType)
Verifies that at least one element in the actual
Iterable has the specified type (matching includes
subclasses of the given type). |
SELF |
hasExactlyElementsOfTypes(Class<?>... types)
Verifies that the actual elements are of the given types in the given order, there should be as many expected types as there are actual elements.
|
SELF |
hasOnlyElementsOfType(Class<?> expectedType)
Verifies that all elements in the actual
Iterable have the specified type (matching includes
subclasses of the given type). |
SELF |
hasOnlyElementsOfTypes(Class<?>... types)
Verifies that all elements of the actual group are instances of the given types.
|
SELF |
hasOnlyOneElementSatisfying(Consumer<? super ELEMENT> elementAssertions)
Deprecated.
use
singleElement() instead |
SELF |
hasSameClassAs(Object other)
Verifies that the actual value has the same class as the given object.
|
SELF |
hasSameElementsAs(Iterable<? extends ELEMENT> iterable)
Verifies that actual contains all the elements of the given iterable and nothing else, in any order
and ignoring duplicates (i.e.
|
SELF |
hasSameSizeAs(Iterable<?> other)
Verifies that the actual group has the same size as given
Iterable. |
SELF |
hasSameSizeAs(Object other)
Verifies that the actual group has the same size as given array.
|
SELF |
hasSize(int expected)
Verifies that the number of values in the actual group is equal to the given one.
|
SELF |
hasSizeBetween(int lowerBoundary,
int higherBoundary)
Verifies that the number of values in the actual iterable is between the given boundaries (inclusive).
|
SELF |
hasSizeGreaterThan(int boundary)
Verifies that the number of values in the actual iterable is greater than the given boundary.
|
SELF |
hasSizeGreaterThanOrEqualTo(int boundary)
Verifies that the number of values in the actual iterable is greater than or equal to the given boundary.
|
SELF |
hasSizeLessThan(int boundary)
Verifies that the number of values in the actual iterable is less than the given boundary.
|
SELF |
hasSizeLessThanOrEqualTo(int boundary)
Verifies that the number of values in the actual iterable is less than or equal to the given boundary.
|
SELF |
hasToString(String expectedToString)
Verifies that actual
actual.toString() is equal to the given String. |
SELF |
have(Condition<? super ELEMENT> condition)
Verifies that all elements satisfy the given condition.
|
SELF |
haveAtLeast(int times,
Condition<? super ELEMENT> condition)
Verifies that there are at least n elements in the actual group satisfying the given condition.
|
SELF |
haveAtLeastOne(Condition<? super ELEMENT> condition)
Verifies that there is at least one element in the actual group satisfying the given condition.
|
SELF |
haveAtMost(int times,
Condition<? super ELEMENT> condition)
Verifies that there are at most n elements in the actual group satisfying the given condition.
|
SELF |
haveExactly(int times,
Condition<? super ELEMENT> condition)
Verifies that there are exactly n elements in the actual group satisfying the given condition.
|
SELF |
inBinary()
Enable binary representation of Iterable elements instead of standard representation in error messages.
|
SELF |
inHexadecimal()
Enable hexadecimal representation of Iterable elements instead of standard representation in error messages.
|
SELF |
is(Condition<? super ACTUAL> condition)
Verifies that the actual value satisfies the given condition.
|
void |
isEmpty()
Verifies that the actual group of values is empty.
|
SELF |
isEqualTo(Object expected)
Verifies that the actual value is equal to the given one.
|
SELF |
isExactlyInstanceOf(Class<?> type)
Verifies that the actual value is exactly an instance of the given type.
|
SELF |
isIn(Iterable<?> values)
Verifies that the actual value is present in the given iterable.
|
SELF |
isIn(Object... values)
Verifies that the actual value is present in the given array of values.
|
SELF |
isInstanceOf(Class<?> type)
Verifies that the actual value is an instance of the given type.
|
SELF |
isInstanceOfAny(Class<?>... types)
Verifies that the actual value is an instance of any of the given types.
|
SELF |
isNot(Condition<? super ACTUAL> condition)
Verifies that the actual value does not satisfy the given condition.
|
SELF |
isNotEmpty()
Verifies that the actual group of values is not empty.
|
SELF |
isNotEqualTo(Object other)
Verifies that the actual value is not equal to the given one.
|
SELF |
isNotExactlyInstanceOf(Class<?> type)
Verifies that the actual value is not exactly an instance of given type.
|
SELF |
isNotIn(Iterable<?> values)
Verifies that the actual value is not present in the given iterable.
|
SELF |
isNotIn(Object... values)
Verifies that the actual value is not present in the given array of values.
|
SELF |
isNotInstanceOf(Class<?> type)
Verifies that the actual value is not an instance of the given type.
|
SELF |
isNotInstanceOfAny(Class<?>... types)
Verifies that the actual value is not an instance of any of the given types.
|
SELF |
isNotNull()
Verifies that the actual value is not
null. |
SELF |
isNotOfAnyClassIn(Class<?>... types)
Verifies that the actual value type is not in given types.
|
SELF |
isNotSameAs(Object other)
Verifies that the actual value is not the same as the given one, ie using == comparison.
|
void |
isNullOrEmpty()
Verifies that the actual group of values is
null or empty. |
SELF |
isOfAnyClassIn(Class<?>... types)
Verifies that the actual value type is in given types.
|
SELF |
isSameAs(Object expected)
Verifies that the actual value is the same as the given one, ie using == comparison.
|
SELF |
isSubsetOf(ELEMENT... values)
Verifies that all the elements of actual are present in the given values.
|
SELF |
isSubsetOf(Iterable<? extends ELEMENT> values)
Verifies that all the elements of actual are present in the given
Iterable. |
protected SELF |
isSubsetOfForProxy(ELEMENT[] values) |
ELEMENT_ASSERT |
last()
Navigate and allow to perform assertions on the last element of the
Iterable under test. |
<ASSERT extends AbstractAssert<?,?>> |
last(InstanceOfAssertFactory<?,ASSERT> assertFactory)
Navigate and allow to perform assertions on the last element of the
Iterable under test. |
AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> |
map(Function<? super ELEMENT,?>... mappers)
|
<V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> |
map(Function<? super ELEMENT,V> mapper)
Maps the Iterable's elements under test by applying a mapping function, the resulting list becomes the instance under test.
|
<V,EXCEPTION extends Exception> |
map(ThrowingExtractor<? super ELEMENT,V,EXCEPTION> mapper)
Maps the Iterable's elements by applying the given mapping function (which might throw an exception), the returned list
becomes the instance under test.
|
protected String |
navigationDescription(String propertyName) |
protected abstract SELF |
newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable)
This methods is needed to build a new concrete instance of AbstractIterableAssert after a filtering operation is executed.
|
protected SELF |
newAbstractIterableAssertForProxy(List<ELEMENT> filteredIterable) |
SELF |
noneMatch(Predicate<? super ELEMENT> predicate)
Verifies that no elements match the given
Predicate. |
SELF |
noneSatisfy(Consumer<? super ELEMENT> restrictions)
Verifies that no elements satisfy the given restrictions expressed as a
Consumer. |
SELF |
noneSatisfy(ThrowingConsumer<? super ELEMENT> restrictions)
Verifies that no elements satisfy the given restrictions expressed as a
Consumer. |
SELF |
overridingErrorMessage(String newErrorMessage,
Object... args)
Overrides AssertJ default error message by the given one.
|
SELF |
satisfiesExactly(Consumer<? super ELEMENT>... requirements)
Verifies that each element satisfies the requirements corresponding to its index, so the first element must satisfy the
first requirements, the second element the second requirements etc...
|
SELF |
satisfiesExactly(ThrowingConsumer<? super ELEMENT>... requirements)
Verifies that each element satisfies the requirements corresponding to its index, so the first element must satisfy the
first requirements, the second element the second requirements etc...
|
protected SELF |
satisfiesExactlyForProxy(Consumer<? super ELEMENT>[] requirements) |
SELF |
satisfiesExactlyInAnyOrder(Consumer<? super ELEMENT>... requirements)
Verifies that at least one combination of iterable elements exists that satisfies the consumers in order (there must be as
many consumers as iterable elements and once a consumer is matched it cannot be reused to match other elements).
|
SELF |
satisfiesExactlyInAnyOrder(ThrowingConsumer<? super ELEMENT>... requirements)
Verifies that at least one combination of iterable elements exists that satisfies the
ThrowingConsumers in order (there must be as
many consumers as iterable elements and once a consumer is matched it cannot be reused to match other elements). |
protected SELF |
satisfiesExactlyInAnyOrderForProxy(Consumer<? super ELEMENT>[] requirements) |
ELEMENT_ASSERT |
singleElement()
Verifies that the
Iterable under test contains a single element and allows to perform assertions on that element. |
<ASSERT extends AbstractAssert<?,?>> |
singleElement(InstanceOfAssertFactory<?,ASSERT> assertFactory)
Verifies that the
Iterable under test contains a single element and allows to perform assertions on that element,
the assertions are strongly typed according to the given AssertFactory parameter. |
AbstractIterableSizeAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT> |
size()
Returns an
Assert object that allows performing assertions on the size of the Iterable under test. |
SELF |
startsWith(ELEMENT... sequence)
Verifies that the actual group starts with the given sequence of objects, without any other objects between them.
|
protected SELF |
startsWithForProxy(ELEMENT[] sequence) |
protected abstract ELEMENT_ASSERT |
toAssert(ELEMENT value,
String description)
This method is used in navigating assertions like
first(), last() and element(int) to build the
assertion for the given element navigated to. |
SELF |
usingComparator(Comparator<? super ACTUAL> customComparator)
Use the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.
|
SELF |
usingComparator(Comparator<? super ACTUAL> customComparator,
String customComparatorDescription)
Use the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.
|
<T> SELF |
usingComparatorForElementFieldsWithNames(Comparator<T> comparator,
String... elementPropertyOrFieldNames)
Deprecated.
This method is used with
usingFieldByFieldElementComparator() which is deprecated in favor of
usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) or usingRecursiveComparison().
When using
and when using
|
<T> SELF |
usingComparatorForElementFieldsWithType(Comparator<T> comparator,
Class<T> type)
Deprecated.
This method is used with
usingFieldByFieldElementComparator() which is deprecated in favor of
usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) or usingRecursiveComparison().
When using
and when using
|
<T> SELF |
usingComparatorForType(Comparator<T> comparator,
Class<T> type)
Allows to set a specific comparator for the given type of elements or their fields.
|
protected SELF |
usingComparisonStrategy(ComparisonStrategy comparisonStrategy) |
SELF |
usingDefaultComparator()
Revert to standard comparison for the incoming assertion checks.
|
SELF |
usingDefaultElementComparator()
Revert to standard comparison for incoming assertion group element checks.
|
SELF |
usingElementComparator(Comparator<? super ELEMENT> elementComparator)
Use given custom comparator instead of relying on actual type A
equals method to compare group
elements for incoming assertion checks. |
SELF |
usingElementComparatorIgnoringFields(String... fields)
Deprecated.
This method is deprecated because it performs a shallow field by field comparison, i.e. elements are
compared field by field but the fields are compared with equals, use
usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...) instead.
See https://assertj.github.io/doc/#assertj-core-recursive-comparison |
SELF |
usingElementComparatorOnFields(String... fields)
Deprecated.
This method is deprecated because it performs a shallow field by field comparison, i.e. elements are
compared field by field but the fields are compared with equals, use
usingRecursiveFieldByFieldElementComparatorOnFields(String...) instead.
See https://assertj.github.io/doc/#assertj-core-recursive-comparison |
SELF |
usingFieldByFieldElementComparator()
Deprecated.
This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared
field by field but the fields are compared with equals, use
usingRecursiveFieldByFieldElementComparator()
or usingRecursiveComparison() instead to perform a true recursive comparison.
See https://assertj.github.io/doc/#assertj-core-recursive-comparison |
RecursiveComparisonAssert<?> |
usingRecursiveComparison()
Enable using a recursive field by field comparison strategy when calling the chained
RecursiveComparisonAssert, |
RecursiveComparisonAssert<?> |
usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration)
Same as
usingRecursiveComparison() but allows to specify your own RecursiveComparisonConfiguration. |
SELF |
usingRecursiveFieldByFieldElementComparator()
Enable using a recursive field by field comparison strategy similar to
usingRecursiveComparison() but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists). |
SELF |
usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration configuration)
Enable using a recursive field by field comparison strategy similar to
usingRecursiveComparison() but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists). |
SELF |
usingRecursiveFieldByFieldElementComparatorIgnoringFields(String... fields)
The assertions chained after this method will use a recursive field by field comparison on all fields (including inherited
fields) except the given ones instead of relying on the element
equals method. |
SELF |
usingRecursiveFieldByFieldElementComparatorOnFields(String... fields)
The assertions chained after this method will use a recursive field by field comparison on the given fields (including
inherited fields) instead of relying on the element
equals method. |
SELF |
withFailMessage(String newErrorMessage,
Object... args)
Alternative method for
AbstractAssert.overridingErrorMessage(java.lang.String, java.lang.Object...) |
SELF |
withThreadDumpOnError()
In case of an assertion error, a thread dump will be printed to
System.err. |
<OTHER_ELEMENT> |
zipSatisfy(Iterable<OTHER_ELEMENT> other,
BiConsumer<? super ELEMENT,OTHER_ELEMENT> zipRequirements)
Verifies that the zipped pairs of actual and other elements, i.e: (actual 1st element, other 1st element), (actual 2nd element, other 2nd element), ...
|
areEqual, asInstanceOf, asList, assertionError, asString, descriptionText, doesNotHaveSameHashCodeAs, doesNotHaveToString, equals, extracting, extracting, failure, failureWithActualExpected, failWithActualExpectedAndMessage, failWithMessage, getWritableAssertionInfo, hashCode, hasSameHashCodeAs, isElementOfCustomAssert, isInstanceOfSatisfying, isNull, matches, matches, newListAssertInstance, overridingErrorMessage, satisfies, satisfies, satisfies, satisfiesAnyOf, satisfiesAnyOf, satisfiesAnyOfForProxy, satisfiesForProxy, setCustomRepresentation, setDescriptionConsumer, setPrintAssertionsDescription, throwAssertionError, withFailMessage, withRepresentationclone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitasprotected Iterables iterables
public void isNullOrEmpty()
null or empty.
Example:
// assertions will pass
List<String> strings = new ArrayList<>();
assertThat(strings).isNullOrEmpty();
assertThat(new int[] { }).isNullOrEmpty();
// assertions will fail
assertThat(new String[] { "a", "b"}).isNullOrEmpty();
assertThat(Arrays.asList(1, 2, 3)).isNullOrEmpty();isNullOrEmpty in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>public void isEmpty()
Example:
// assertions will pass
assertThat(new ArrayList()).isEmpty();
assertThat(new int[] { }).isEmpty();
// assertions will fail
assertThat(new String[] { "a", "b" }).isEmpty();
assertThat(Arrays.asList(1, 2, 3)).isEmpty();isEmpty in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>public SELF isNotEmpty()
Example:
// assertions will pass
assertThat(new String[] { "a", "b" }).isNotEmpty();
assertThat(Arrays.asList(1, 2, 3)).isNotEmpty();
// assertions will fail
assertThat(new ArrayList()).isNotEmpty();
assertThat(new int[] { }).isNotEmpty();isNotEmpty in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>this assertion object.public SELF hasSize(int expected)
Example:
// assertions will pass
assertThat(new String[] { "a", "b" }).hasSize(2);
assertThat(Arrays.asList(1, 2, 3)).hasSize(3);
// assertions will fail
assertThat(new ArrayList()).hasSize(1);
assertThat(new int[] { 1, 2, 3 }).hasSize(2);hasSize in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>expected - the expected number of values in the actual group.this assertion object.public SELF hasSizeGreaterThan(int boundary)
Example:
// assertion will pass
assertThat(Arrays.asList(1, 2, 3)).hasSizeGreaterThan(2);
// assertion will fail
assertThat(Arrays.asList(1, 2, 3)).hasSizeGreaterThan(3);hasSizeGreaterThan in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>boundary - the given value to compare the actual size to.this assertion object.AssertionError - if the number of values of the actual iterable is not greater than the boundary.public SELF hasSizeGreaterThanOrEqualTo(int boundary)
Example:
// assertions will pass
assertThat(Arrays.asList(1, 2, 3)).hasSizeGreaterThanOrEqualTo(1)
.hasSizeGreaterThanOrEqualTo(3);
// assertion will fail
assertThat(Arrays.asList(1, 2, 3)).hasSizeGreaterThanOrEqualTo(4);hasSizeGreaterThanOrEqualTo in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>boundary - the given value to compare the actual size to.this assertion object.AssertionError - if the number of values of the actual iterable is not greater than or equal to the boundary.public SELF hasSizeLessThan(int boundary)
Example:
// assertion will pass
assertThat(Arrays.asList(1, 2, 3)).hasSizeLessThan(4);
// assertion will fail
assertThat(Arrays.asList(1, 2, 3)).hasSizeLessThan(3);hasSizeLessThan in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>boundary - the given value to compare the actual size to.this assertion object.AssertionError - if the number of values of the actual iterable is not less than the boundary.public SELF hasSizeLessThanOrEqualTo(int boundary)
Example:
// assertions will pass
assertThat(Arrays.asList(1, 2, 3)).hasSizeLessThanOrEqualTo(5)
.hasSizeLessThanOrEqualTo(3);
// assertion will fail
assertThat(Arrays.asList(1, 2, 3)).hasSizeLessThanOrEqualTo(2);hasSizeLessThanOrEqualTo in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>boundary - the given value to compare the actual size to.this assertion object.AssertionError - if the number of values of the actual iterable is not less than or equal to the boundary.public SELF hasSizeBetween(int lowerBoundary, int higherBoundary)
Example:
// assertions will pass
assertThat(Arrays.asList(1, 2, 3)).hasSizeBetween(2, 3)
.hasSizeBetween(3, 4)
.hasSizeBetween(3, 3);
// assertion will fail
assertThat(Arrays.asList(1, 2, 3)).hasSizeBetween(4, 6);hasSizeBetween in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>lowerBoundary - the lower boundary compared to which actual size should be greater than or equal to.higherBoundary - the higher boundary compared to which actual size should be less than or equal to.this assertion object.AssertionError - if the number of values of the actual iterable is not between the boundaries.@Deprecated public SELF hasOnlyOneElementSatisfying(Consumer<? super ELEMENT> elementAssertions)
singleElement() insteadIterable satisfies the given assertions expressed as a Consumer,
if it does not, only the first error is reported, use SoftAssertions to get all the errors.
Example:
List<Jedi> jedis = asList(new Jedi("Yoda", "red"));
// assertions will pass
assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("Y"));
assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> {
assertThat(yoda.getName()).isEqualTo("Yoda");
assertThat(yoda.getLightSaberColor()).isEqualTo("red");
});
// assertions will fail
assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("Vad"));
// fail as one the assertions is not satisfied
assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> {
assertThat(yoda.getName()).isEqualTo("Yoda");
assertThat(yoda.getLightSaberColor()).isEqualTo("purple");
});
// fail but only report the first error
assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> {
assertThat(yoda.getName()).isEqualTo("Luke");
assertThat(yoda.getLightSaberColor()).isEqualTo("green");
});
// fail and reports the errors thanks to Soft assertions
assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> {
SoftAssertions softly = new SoftAssertions();
softly.assertThat(yoda.getName()).isEqualTo("Luke");
softly.assertThat(yoda.getLightSaberColor()).isEqualTo("green");
softly.assertAll();
});
// even if the assertion is correct, there are too many jedis !
jedis.add(new Jedi("Luke", "green"));
assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("Yo"));hasOnlyOneElementSatisfying in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>elementAssertions - the assertions to perform on the unique element.this assertion object.AssertionError - if the Iterable does not have a unique element.AssertionError - if the Iterable's unique element does not satisfy the given assertions.public SELF hasSameSizeAs(Object other)
Parameter is declared as Object to accept both Object[] and primitive arrays (e.g. int[]).
Example: int[] oneTwoThree = {1, 2, 3};
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass
assertThat(elvesRings).hasSameSizeAs(oneTwoThree);
// assertions will fail
assertThat(elvesRings).hasSameSizeAs(new int[] { 1, 2});
assertThat(elvesRings).hasSameSizeAs(new int[] { 1, 2, 3, 4});hasSameSizeAs in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>other - the array to compare size with actual group.this assertion object.public SELF hasSameSizeAs(Iterable<?> other)
Iterable.
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass
assertThat(elvesRings).hasSameSizeAs(abc);
// assertions will fail
assertThat(elvesRings).hasSameSizeAs(Arrays.asList(1, 2));
assertThat(elvesRings).hasSameSizeAs(Arrays.asList(1, 2, 3, 4));hasSameSizeAs in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>other - the Iterable to compare size with actual group.this assertion object.@SafeVarargs public final SELF contains(ELEMENT... values)
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
// assertions will pass
assertThat(abc).contains("b", "a");
assertThat(abc).contains("b", "a", "b");
// assertion will fail
assertThat(abc).contains("d");
If you want to specify the elements to check with an Iterable, use containsAll(Iterable) instead.
contains in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the given values.this assertion object.@SafeVarargs public final SELF containsOnly(ELEMENT... values)
If you need to check exactly the elements and their duplicates use:
containsExactly(Object...) if the order does mattercontainsExactlyInAnyOrder(Object...) if the order does not matterExample:
Iterable<String> abc = newArrayList("a", "b", "c");
// assertions will pass as order does not matter
assertThat(abc).containsOnly("c", "b", "a");
// duplicates are ignored
assertThat(abc).containsOnly("a", "a", "b", "c", "c");
// ... on both actual and expected values
assertThat(asList("a", "a", "b")).containsOnly("a", "b")
.containsOnly("a", "a", "b", "b");
// assertion will fail because "c" is missing in the given values
assertThat(abc).containsOnly("a", "b");
// assertion will fail because "d" is missing in abc (use isSubsetOf if you want this assertion to pass)
assertThat(abc).containsOnly("a", "b", "c", "d");
If you need to check that actual is a subset of the given values, use ObjectEnumerableAssert.isSubsetOf(Object...).
If you want to specify the elements to check with an Iterable, use containsOnlyElementsOf(Iterable) instead.
containsOnly in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the given values.this assertion object.@SafeVarargs public final SELF containsOnlyOnce(ELEMENT... values)
Examples :
// lists are used in the examples but it would also work with arrays
// assertions will pass
assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("winter");
assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("coming", "winter");
// assertions will fail
assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("Lannister");
assertThat(newArrayList("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark");
assertThat(newArrayList("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark", "Lannister", "Arya");containsOnlyOnce in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the given values.this assertion object.public SELF containsOnlyNulls()
Example:
// assertion will pass
Iterable<String> items = Arrays.asList(null, null, null);
assertThat(items).containsOnlyNulls();
// assertion will fail because items2 contains a not null element
Iterable<String> items2 = Arrays.asList(null, null, "notNull");
assertThat(items2).containsOnlyNulls();
// assertion will fail since an empty iterable does not contain any elements and therefore no null ones.
Iterable<String> empty = new ArrayList<>();
assertThat(empty).containsOnlyNulls();containsOnlyNulls in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>this assertion object.@SafeVarargs public final SELF containsExactly(ELEMENT... values)
HashSet, prefer ObjectEnumerableAssert.containsOnly(Object...) in that case).
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass
assertThat(elvesRings).containsExactly(vilya, nenya, narya);
// assertion will fail as actual and expected order differ
assertThat(elvesRings).containsExactly(nenya, vilya, narya);
If you want to specify the elements to check with an Iterable, use containsExactlyElementsOf(Iterable) instead.
containsExactly in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the given values.this assertion object.@SafeVarargs public final SELF containsExactlyInAnyOrder(ELEMENT... values)
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);
// assertion will pass
assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);
// assertion will fail as vilya is contained twice in elvesRings.
assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);
If you want to specify the elements to check with an Iterable, use containsExactlyInAnyOrderElementsOf(Iterable) instead.
containsExactlyInAnyOrder in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the given values.this assertion object.protected SELF containsExactlyInAnyOrderForProxy(ELEMENT[] values)
public SELF containsExactlyInAnyOrderElementsOf(Iterable<? extends ELEMENT> values)
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);
Iterable<Ring> elvesRingsSomeMissing = newArrayList(vilya, nenya, narya);
Iterable<Ring> elvesRingsDifferentOrder = newArrayList(nenya, narya, vilya, vilya);
// assertion will pass
assertThat(elvesRings).containsExactlyInAnyOrderElementsOf(elvesRingsDifferentOrder);
// assertion will fail as vilya is contained twice in elvesRings.
assertThat(elvesRings).containsExactlyInAnyOrderElementsOf(elvesRingsSomeMissing);
If you want to directly specify the elements to check, use containsExactlyInAnyOrder(Object...) instead.
containsExactlyInAnyOrderElementsOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the given values.this assertion object.public SELF isSubsetOf(Iterable<? extends ELEMENT> values)
Iterable.
Example:
// an Iterable is used in the example but it would also work with an array
List<Ring> ringsOfPower = newArrayList(oneRing, vilya, nenya, narya, dwarfRing, manRing);
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass:
assertThat(elvesRings).isSubsetOf(ringsOfPower);
// assertion will fail:
assertThat(elvesRings).isSubsetOf(newArrayList(nenya, narya));
If you want to directly specify the set of elements, use isSubsetOf(Object...) instead.
isSubsetOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the Iterable that should contain all actual elements.@SafeVarargs public final SELF isSubsetOf(ELEMENT... values)
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass:
assertThat(elvesRings).isSubsetOf(vilya, nenya, narya)
.isSubsetOf(vilya, nenya, narya, dwarfRing);
// assertions will fail:
assertThat(elvesRings).isSubsetOf(vilya, nenya);
assertThat(elvesRings).isSubsetOf(vilya, nenya, dwarfRing);
If you want to specify the set of elements an Iterable, use isSubsetOf(Iterable) instead.
isSubsetOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the values that should be used for checking the elements of actual.@SafeVarargs public final SELF containsSequence(ELEMENT... sequence)
Use ObjectEnumerableAssert.containsSubsequence(Object...) to allow values between the expected sequence values.
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).containsSequence(vilya, nenya)
.containsSequence(nenya, narya);
// assertions will fail, the elements order is correct but there is a value between them (nenya)
assertThat(elvesRings).containsSequence(vilya, narya);
assertThat(elvesRings).containsSequence(nenya, vilya);
If you want to specify the sequence to check with an Iterable, use containsSequence(Iterable) instead.
containsSequence in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>sequence - the sequence of objects to look for.public SELF containsSequence(Iterable<? extends ELEMENT> sequence)
Use ObjectEnumerableAssert.containsSubsequence(Iterable) to allow values between the expected sequence values.
Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).containsSequence(newArrayList(vilya, nenya))
.containsSequence(newArrayList(nenya, narya));
// assertions will fail, the elements order is correct but there is a value between them (nenya)
assertThat(elvesRings).containsSequence(newArrayList(vilya, narya));
assertThat(elvesRings).containsSequence(newArrayList(nenya, vilya));
If you want to directly specify the elements of the sequence to check, use containsSequence(Object...) instead.
containsSequence in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>sequence - the sequence of objects to look for.@SafeVarargs public final SELF doesNotContainSequence(ELEMENT... sequence)
Use ObjectEnumerableAssert.doesNotContainSubsequence(Object...) to also ensure the sequence does not exist with values between the expected sequence values.
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass, the elements order is correct but there is a value between them (nenya)
assertThat(elvesRings).doesNotContainSequence(vilya, narya)
.doesNotContainSequence(nenya, vilya);
// assertions will fail
assertThat(elvesRings).doesNotContainSequence(vilya, nenya);
assertThat(elvesRings).doesNotContainSequence(nenya, narya);
If you want to specify the sequence not to find with an Iterable, use doesNotContainSequence(Iterable) instead.
doesNotContainSequence in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>sequence - the sequence of objects to look for.public SELF doesNotContainSequence(Iterable<? extends ELEMENT> sequence)
Use ObjectEnumerableAssert.doesNotContainSubsequence(Iterable) to also ensure the sequence does not exist with values between the sequence values.
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass, the elements order is correct but there is a value between them (nenya)
assertThat(elvesRings).doesNotContainSequence(newArrayList(vilya, narya))
.doesNotContainSequence(newArrayList(nenya, vilya));
// assertions will fail
assertThat(elvesRings).doesNotContainSequence(newArrayList(vilya, nenya));
assertThat(elvesRings).doesNotContainSequence(newArrayList(nenya, narya));
If you want to directly specify the elements of the sequence not to find, use doesNotContainSequence(Object...) instead.
doesNotContainSequence in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>sequence - the sequence of objects to look for.@SafeVarargs public final SELF containsSubsequence(ELEMENT... subsequence)
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).containsSubsequence(vilya, nenya)
.containsSubsequence(vilya, narya);
// assertion will fail
assertThat(elvesRings).containsSubsequence(nenya, vilya);
If you want to specify the elements of the subsequence to check with an Iterable, use containsSubsequence(Iterable) instead.
containsSubsequence in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>subsequence - the sequence of objects to look for.public SELF containsSubsequence(Iterable<? extends ELEMENT> subsequence)
Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).containsSubsequence(newArrayList(vilya, nenya))
.containsSubsequence(newArrayList(vilya, narya));
// assertion will fail
assertThat(elvesRings).containsSubsequence(newArrayList(nenya, vilya));
If you want to directly specify the subsequence to check, use containsSubsequence(Object...) instead.
containsSubsequence in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>subsequence - the sequence of objects to look for.@SafeVarargs public final SELF doesNotContainSubsequence(ELEMENT... subsequence)
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).doesNotContainSubsequence(nenya, vilya)
.doesNotContainSubsequence(narya, vilya);
// assertion will fail
assertThat(elvesRings).doesNotContainSubsequence(vilya, nenya);
assertThat(elvesRings).doesNotContainSubsequence(vilya, narya);
If you want to specify the subsequence not to find with an Iterable, use doesNotContainSubsequence(Iterable) instead.
doesNotContainSubsequence in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>subsequence - the sequence of objects to look for.protected SELF doesNotContainSubsequenceForProxy(ELEMENT[] subsequence)
public SELF doesNotContainSubsequence(Iterable<? extends ELEMENT> subsequence)
Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).doesNotContainSubsequence(newArrayList(nenya, vilya));
.doesNotContainSubsequence(newArrayList(narya, vilya));
// assertion will fail
assertThat(elvesRings).doesNotContainSubsequence(newArrayList(vilya, nenya));
assertThat(elvesRings).doesNotContainSubsequence(newArrayList(vilya, narya));
If you want to directly specify the elements of the subsequence not to find, use doesNotContainSubsequence(Object...) instead.
doesNotContainSubsequence in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>subsequence - the sequence of objects to look for.@SafeVarargs public final SELF doesNotContain(ELEMENT... values)
ObjectEnumerableAssertExample:
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertions will pass
assertThat(abc).doesNotContain("d")
.doesNotContain("d", "e");
// assertions will fail
assertThat(abc).doesNotContain("a");
assertThat(abc).doesNotContain("a", "b");
assertThat(abc).doesNotContain("c", "d");
If you want to specify the elements not to find with an Iterable, use doesNotContainAnyElementsOf(Iterable) instead.
doesNotContain in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the given values.this assertion object.public SELF doesNotContainAnyElementsOf(Iterable<? extends ELEMENT> iterable)
ObjectEnumerableAssertIterable (i.e. none).
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
// assertion succeeds:
assertThat(actual).doesNotContainAnyElementsOf(newArrayList("d", "e"));
// assertion fails:
assertThat(actual).doesNotContainAnyElementsOf(newArrayList("d", "e", "a"));
If you want to directly specify the elements not to find, use doesNotContain(Object...) instead.
doesNotContainAnyElementsOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>iterable - the Iterable whose elements must not be in the actual group.this assertion object.public SELF doesNotHaveDuplicates()
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> lotsOfAs = newArrayList("a", "a", "a");
// assertion will pass
assertThat(abc).doesNotHaveDuplicates();
// assertion will fail
assertThat(lotsOfAs).doesNotHaveDuplicates();doesNotHaveDuplicates in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>this assertion object.@SafeVarargs public final SELF startsWith(ELEMENT... sequence)
ObjectEnumerableAssert.containsSequence(Object...), but it also verifies that the first element in the
sequence is also first element of the actual group.
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertions will pass
assertThat(abc).startsWith("a")
.startsWith("a", "b");
// assertion will fail
assertThat(abc).startsWith("c");startsWith in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>sequence - the sequence of objects to look for.@SafeVarargs public final SELF endsWith(ELEMENT first, ELEMENT... rest)
ObjectEnumerableAssert.containsSequence(Object...), but it also verifies that the last element in the
sequence is also last element of the actual group.
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertions will pass
assertThat(abc).endsWith("c")
.endsWith("b", "c");
// assertions will fail
assertThat(abc).endsWith("a");
assertThat(abc).endsWith("a", "b");endsWith in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>first - the first element of the sequence of objects to look for.rest - the rest of the sequence of objects to look for.public SELF endsWith(ELEMENT[] sequence)
ObjectEnumerableAssert.containsSequence(Object...), but it also verifies that the last element in the
sequence is also last element of the actual group.
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertions will pass
assertThat(abc).endsWith(new String[0])
.endsWith(new String[] {"c"})
.endsWith(new String[] {"b", "c"});
// assertions will fail
assertThat(abc).endsWith(new String[] {"a"});
assertThat(abc).endsWith(new String[] {"a", "b"});endsWith in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>sequence - the sequence of objects to look for.public SELF containsNull()
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abNull = newArrayList("a", "b", null);
// assertion will pass
assertThat(abNull).containsNull();
// assertion will fail
assertThat(abc).containsNull();containsNull in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>this assertion object.public SELF doesNotContainNull()
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abNull = newArrayList("a", "b", null);
// assertion will pass
assertThat(abc).doesNotContainNull();
// assertion will fail
assertThat(abNull).doesNotContainNull();doesNotContainNull in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>this assertion object.public SELF are(Condition<? super ELEMENT> condition)
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
Condition<String> singleCharacterString
= new Condition<>(s -> s.length() == 1, "single character String");
// assertion will pass
assertThat(abc).are(singleCharacterString);
// assertion will fail
assertThat(abcc).are(singleCharacterString);are in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>condition - the given condition.this object.public SELF areNot(Condition<? super ELEMENT> condition)
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
Condition<String> moreThanOneCharacter =
= new Condition<>(s -> s.length() > 1, "more than one character");
// assertion will pass
assertThat(abc).areNot(moreThanOneCharacter);
// assertion will fail
assertThat(abcc).areNot(moreThanOneCharacter);areNot in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>condition - the given condition.this object.public SELF have(Condition<? super ELEMENT> condition)
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
Condition<String> onlyOneCharacter =
= new Condition<>(s -> s.length() == 1, "only one character");
// assertion will pass
assertThat(abc).have(onlyOneCharacter);
// assertion will fail
assertThat(abcc).have(onlyOneCharacter);have in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>condition - the given condition.this object.public SELF doNotHave(Condition<? super ELEMENT> condition)
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
Condition<String> moreThanOneCharacter =
= new Condition<>(s -> s.length() > 1, "more than one character");
// assertion will pass
assertThat(abc).doNotHave(moreThanOneCharacter);
// assertion will fail
assertThat(abcc).doNotHave(moreThanOneCharacter);doNotHave in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>condition - the given condition.this object.public SELF areAtLeastOne(Condition<? super ELEMENT> condition)
This method is an alias for areAtLeast(1, condition).
Example:
// jedi is a Condition<String>
assertThat(newLinkedHashSet("Luke", "Solo", "Leia")).areAtLeastOne(jedi);areAtLeastOne in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>condition - the given condition.this assertion object.ObjectEnumerableAssert.haveAtLeast(int, Condition)public SELF areAtLeast(int times, Condition<? super ELEMENT> condition)
Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number");
// assertion will pass
oneTwoThree.areAtLeast(2, oddNumber);
// assertion will fail
oneTwoThree.areAtLeast(3, oddNumber);areAtLeast in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>times - the minimum number of times the condition should be verified.condition - the given condition.this object.public SELF areAtMost(int times, Condition<? super ELEMENT> condition)
Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number");
// assertions will pass
oneTwoThree.areAtMost(2, oddNumber)
.areAtMost(3, oddNumber);
// assertion will fail
oneTwoThree.areAtMost(1, oddNumber);areAtMost in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>times - the number of times the condition should be at most verified.condition - the given condition.this object.public SELF areExactly(int times, Condition<? super ELEMENT> condition)
Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number");
// assertion will pass
oneTwoThree.areExactly(2, oddNumber);
// assertions will fail
oneTwoThree.areExactly(1, oddNumber);
oneTwoThree.areExactly(3, oddNumber);areExactly in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>times - the exact number of times the condition should be verified.condition - the given condition.this object.public SELF haveAtLeastOne(Condition<? super ELEMENT> condition)
This method is an alias for haveAtLeast(1, condition).
Example:
Iterable<BasketBallPlayer> bullsPlayers = newArrayList(butler, rose);
// potentialMvp is a Condition<BasketBallPlayer>
assertThat(bullsPlayers).haveAtLeastOne(potentialMvp);haveAtLeastOne in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>condition - the given condition.this assertion object.ObjectEnumerableAssert.haveAtLeast(int, Condition)public SELF haveAtLeast(int times, Condition<? super ELEMENT> condition)
Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number");
// assertion will pass
oneTwoThree.haveAtLeast(2, oddNumber);
// assertion will fail
oneTwoThree.haveAtLeast(3, oddNumber);
This method is an alias for ObjectEnumerableAssert.areAtLeast(int, Condition).haveAtLeast in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>times - the minimum number of times the condition must hold.condition - the given condition.this assertion object.public SELF haveAtMost(int times, Condition<? super ELEMENT> condition)
Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number");
// assertions will pass
oneTwoThree.haveAtMost(2, oddNumber);
oneTwoThree.haveAtMost(3, oddNumber);
// assertion will fail
oneTwoThree.haveAtMost(1, oddNumber);
This method is an alias ObjectEnumerableAssert.areAtMost(int, Condition).haveAtMost in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>times - the maximum number of times the condition must hold.condition - the given condition.this assertion object.public SELF haveExactly(int times, Condition<? super ELEMENT> condition)
Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number");
// assertion will pass
oneTwoThree.haveExactly(2, oddNumber);
// assertions will fail
oneTwoThree.haveExactly(1, oddNumber);
oneTwoThree.haveExactly(3, oddNumber);
This method is an alias ObjectEnumerableAssert.areExactly(int, Condition).haveExactly in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>times - the exact number of times the condition must hold.condition - the given condition.this assertion object.public SELF hasAtLeastOneElementOfType(Class<?> expectedType)
Iterable has the specified type (matching includes
subclasses of the given type).
Example:
List<Number> numbers = new ArrayList<Number>();
numbers.add(1);
numbers.add(2L);
// successful assertion:
assertThat(numbers).hasAtLeastOneElementOfType(Long.class);
// assertion failure:
assertThat(numbers).hasAtLeastOneElementOfType(Float.class);hasAtLeastOneElementOfType in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>expectedType - the expected type.NullPointerException - if the given type is null.AssertionError - if the actual Object group does not have any elements of the given type.public SELF hasOnlyElementsOfType(Class<?> expectedType)
Iterable have the specified type (matching includes
subclasses of the given type).
Example:
List<Number> numbers = new ArrayList<Number>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
// successful assertions:
assertThat(numbers).hasOnlyElementsOfType(Number.class);
assertThat(numbers).hasOnlyElementsOfType(Integer.class);
// assertion failure:
assertThat(numbers).hasOnlyElementsOfType(Long.class);hasOnlyElementsOfType in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>expectedType - the expected type.NullPointerException - if the given type is null.AssertionError - if one element is not of the expected type.public SELF doesNotHaveAnyElementsOfTypes(Class<?>... unexpectedTypes)
Iterable do not have the specified types (including subclasses).
Example:
List<Number> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3.0);
// successful assertions:
assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Float.class);
// assertion failure:
assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Integer.class);doesNotHaveAnyElementsOfTypes in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>unexpectedTypes - the not expected types.NullPointerException - if the given type is null.AssertionError - if one element's type matches the given types.public SELF hasOnlyElementsOfTypes(Class<?>... types)
Example:
Iterable<? extends Object> objects = Arrays.asList("foo", new StringBuilder());
// assertions will pass
assertThat(objects).hasOnlyElementsOfTypes(CharSequence.class)
.hasOnlyElementsOfTypes(String.class, StringBuilder.class);
// assertions will fail
assertThat(objects).hasOnlyElementsOfTypes(Number.class);
assertThat(objects).hasOnlyElementsOfTypes(String.class, Number.class);
assertThat(objects).hasOnlyElementsOfTypes(String.class);hasOnlyElementsOfTypes in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>types - the expected typesthis assertion object.public SELF hasExactlyElementsOfTypes(Class<?>... types)
Example:
Iterable<Object> list = Arrays.asList(1, "a", "b", 1.00);
// assertion succeeds
assertThat(list).hasExactlyElementsOfTypes(Integer.class, String.class, String.class, Double.class);
// assertions fail
// missing second String type
assertThat(list).hasExactlyElementsOfTypes(Integer.class, String.class, Double.class);
// no Float type in actual
assertThat(list).hasExactlyElementsOfTypes(Float.class, String.class, String.class, Double.class);
// correct types but wrong order
assertThat(list).hasExactlyElementsOfTypes(String.class, Integer.class, String.class, Double.class);
// actual has more elements than the specified expected types
assertThat(list).hasExactlyElementsOfTypes(String.class);hasExactlyElementsOfTypes in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>types - the expected typesthis assertion object.public SELF containsAll(Iterable<? extends ELEMENT> iterable)
Iterable, in any order.
Example:
Iterable<String> abc = Arrays.asList("a", "b", "c");
// assertions will pass
assertThat(abc).containsAll(Arrays.asList("b", "c"))
.containsAll(Arrays.asList("a", "b", "c"));
// assertions will fail
assertThat(abc).containsAll(Arrays.asList("d"));
assertThat(abc).containsAll(Arrays.asList("a", "b", "c", "d"));
If you want to directly specify the elements to check, use contains(Object...) instead.
containsAll in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>iterable - the given Iterable we will get elements from.this assertion object.public SELF usingElementComparator(Comparator<? super ELEMENT> elementComparator)
equals method to compare group
elements for incoming assertion checks.
Custom comparator is bound to assertion instance, meaning that if a new assertion is created, it will use default comparison strategy.
Examples : // compares invoices by payee
assertThat(invoiceList).usingComparator(invoicePayeeComparator).isEqualTo(expectedInvoiceList);
// compares invoices by date, doesNotHaveDuplicates and contains both use the given invoice date comparator
assertThat(invoiceList).usingComparator(invoiceDateComparator).doesNotHaveDuplicates().contains(may2010Invoice);
// as assertThat(invoiceList) creates a new assertion, it falls back to standard comparison strategy
// based on Invoice's equal method to compare invoiceList elements to lowestInvoice.
assertThat(invoiceList).contains(lowestInvoice);
// standard comparison : the fellowshipOfTheRing includes Gandalf but not Sauron (believe me) ...
assertThat(fellowshipOfTheRing).contains(gandalf)
.doesNotContain(sauron);
// ... but if we compare only races, Sauron is in fellowshipOfTheRing because he's a Maia like Gandalf.
assertThat(fellowshipOfTheRing).usingElementComparator(raceComparator)
.contains(sauron);usingElementComparator in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>elementComparator - the comparator to use for incoming assertion checks.this assertion object.public SELF usingDefaultElementComparator()
This method should be used to disable a custom comparison strategy set by calling
EnumerableAssert.usingElementComparator(Comparator).
usingDefaultElementComparator in interface EnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>this assertion object.@SafeVarargs public final SELF containsAnyOf(ELEMENT... values)
Iterable contains at least one of the given values.
Example:
Iterable<String> abc = Arrays.asList("a", "b", "c");
// assertions will pass
assertThat(abc).containsAnyOf("b")
.containsAnyOf("b", "c")
.containsAnyOf("a", "b", "c")
.containsAnyOf("a", "b", "c", "d")
.containsAnyOf("e", "f", "g", "b");
// assertions will fail
assertThat(abc).containsAnyOf("d");
assertThat(abc).containsAnyOf("d", "e", "f", "g");containsAnyOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>values - the values whose at least one which is expected to be in the Iterable under test.this assertion object.NullPointerException - if the array of values is null.IllegalArgumentException - if the array of values is empty and the Iterable under test is not empty.AssertionError - if the Iterable under test is null.AssertionError - if the Iterable under test does not contain any of the given values.public SELF containsAnyElementsOf(Iterable<? extends ELEMENT> iterable)
Iterable under test contains at least one of the given Iterable elements.
Example:
Iterable<String> abc = Arrays.asList("a", "b", "c");
// assertions will pass
assertThat(abc).containsAnyElementsOf(Arrays.asList("b"))
.containsAnyElementsOf(Arrays.asList("b", "c"))
.containsAnyElementsOf(Arrays.asList("a", "b", "c"))
.containsAnyElementsOf(Arrays.asList("a", "b", "c", "d"))
.containsAnyElementsOf(Arrays.asList("e", "f", "g", "b"));
// assertions will fail
assertThat(abc).containsAnyElementsOf(Arrays.asList("d"));
assertThat(abc).containsAnyElementsOf(Arrays.asList("d", "e", "f", "g"));containsAnyElementsOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>iterable - the iterable whose at least one element is expected to be in the Iterable under test.this assertion object.NullPointerException - if the iterable of expected values is null.IllegalArgumentException - if the iterable of expected values is empty and the Iterable under test is not empty.AssertionError - if the Iterable under test is null.AssertionError - if the Iterable under test does not contain any of elements from the given Iterable.public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> extracting(String propertyOrField)
It allows you to test a property/field of the Iterable's elements instead of testing the elements themselves, which can be be much less work!
Let's take a look at an example to make things clearer:
// build a list of TolkienCharacters: a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify the names of the TolkienCharacters in fellowshipOfTheRing:
assertThat(fellowshipOfTheRing).extracting("name")
.contains("Boromir", "Gandalf", "Frodo")
.doesNotContain("Sauron", "Elrond");
// you can extract nested properties/fields like the name of the race:
assertThat(fellowshipOfTheRing).extracting("race.name")
.contains("Hobbit", "Elf")
.doesNotContain("Orc");
A property with the given name is searched for first. If it doesn't exist a field with the given name is looked
for. If the field does not exist an IntrospectionError is thrown. By default private fields are read but
you can change this with Assertions.setAllowComparingPrivateFields(boolean). Trying to read a private field
when it's not allowed leads to an IntrospectionError.
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet, you won't be able to make any assumptions on the extracted values
order.
Extracting also support maps, that is, instead of extracting values from an Object, it extracts maps values corresponding to the given keys.
Example:
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee luke = new Employee(2L, new Name("Luke"), 22);
Employee han = new Employee(3L, new Name("Han"), 31);
// build two maps
Map<String, Employee> map1 = new HashMap<>();
map1.put("key1", yoda);
map1.put("key2", luke);
Map<String, Employee> map2 = new HashMap<>();
map2.put("key1", yoda);
map2.put("key2", han);
// instead of a list of objects, we have a list of maps
List<Map<String, Employee>> maps = asList(map1, map2);
// extracting a property in that case = get values from maps using the property as a key
assertThat(maps).extracting("key2").containsExactly(luke, han);
assertThat(maps).extracting("key1").containsExactly(yoda, yoda);
// type safe version
assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);
// it works with several keys, extracted values being wrapped in a Tuple
assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));
// unknown keys leads to null (map behavior)
assertThat(maps).extracting("bad key").containsExactly(null, null);propertyOrField - the property/field to extract from the elements of the Iterable under testIntrospectionError - if no field or property exists with the given name in one of the initial
Iterable's element.public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> extractingResultOf(String method)
It allows you to test the method results of the Iterable's elements instead of testing the elements themselves. This is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String toString() or public String status() instead of public String getStatus()).
Let's take a look at an example to make things clearer:
// Build an array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()
List<WesterosHouse> greatHouses = new ArrayList<WesterosHouse>();
greatHouses.add(new WesterosHouse("Stark", "Winter is Coming"));
greatHouses.add(new WesterosHouse("Lannister", "Hear Me Roar!"));
greatHouses.add(new WesterosHouse("Greyjoy", "We Do Not Sow"));
greatHouses.add(new WesterosHouse("Baratheon", "Our is the Fury"));
greatHouses.add(new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"));
greatHouses.add(new WesterosHouse("Tyrell", "Growing Strong"));
// let's verify the words of the great houses of Westeros:
assertThat(greatHouses).extractingResultOf("sayTheWords")
.contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar")
.doesNotContain("Lannisters always pay their debts");
Following requirements have to be met to extract method results:
Note that the order of extracted results is consistent with the iteration order of the Iterable under test, for
example if it's a HashSet, you won't be able to make any assumptions on the extracted results order.
method - the name of the method which result is to be extracted from the array under testIllegalArgumentException - if no method exists with the given name, or method is not public, or method does
return void, or method accepts arguments.public <P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extractingResultOf(String method, Class<P> extractedType)
It allows you to test the method results of the Iterable's elements instead of testing the elements themselves, it is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String toString() or public String status() instead of public String getStatus()).
Let's take an example to make things clearer:
// Build an array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()
List<WesterosHouse> greatHouses = new ArrayList<WesterosHouse>();
greatHouses.add(new WesterosHouse("Stark", "Winter is Coming"));
greatHouses.add(new WesterosHouse("Lannister", "Hear Me Roar!"));
greatHouses.add(new WesterosHouse("Greyjoy", "We Do Not Sow"));
greatHouses.add(new WesterosHouse("Baratheon", "Our is the Fury"));
greatHouses.add(new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"));
greatHouses.add(new WesterosHouse("Tyrell", "Growing Strong"));
// let's verify the words of the great houses of Westeros:
assertThat(greatHouses).extractingResultOf("sayTheWords", String.class)
.contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar")
.doesNotContain("Lannisters always pay their debts");
Following requirements have to be met to extract method results:
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet, you won't be able to make any assumptions of the extracted values
order.
P - the type of elements extracted.method - the name of the method which result is to be extracted from the array under testextractedType - type of element of the extracted ListIllegalArgumentException - if no method exists with the given name, or method is not public, or method does
return void or method accepts arguments.public <P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extracting(String propertyOrField, Class<P> extractingType)
It allows you to test a property/field of the Iterable's elements instead of testing the elements themselves, which can be much less work!
Let's take an example to make things clearer:
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify the names of TolkienCharacter in fellowshipOfTheRing:
assertThat(fellowshipOfTheRing).extracting("name", String.class)
.contains("Boromir", "Gandalf", "Frodo")
.doesNotContain("Sauron", "Elrond");
// you can extract nested property/field like the name of Race:
assertThat(fellowshipOfTheRing).extracting("race.name", String.class)
.contains("Hobbit", "Elf")
.doesNotContain("Orc");
A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked
for, if the field does not exist an IntrospectionError is thrown, by default private fields are read but
you can change this with Assertions.setAllowComparingPrivateFields(boolean), trying to read a private field
when it's not allowed leads to an IntrospectionError.
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet, you won't be able to make any assumptions on the extracted values
order.
Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values corresponding to the given keys.
Example:
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee luke = new Employee(2L, new Name("Luke"), 22);
Employee han = new Employee(3L, new Name("Han"), 31);
// build two maps
Map<String, Employee> map1 = new HashMap<>();
map1.put("key1", yoda);
map1.put("key2", luke);
Map<String, Employee> map2 = new HashMap<>();
map2.put("key1", yoda);
map2.put("key2", han);
// instead of a list of objects, we have a list of maps
List<Map<String, Employee>> maps = asList(map1, map2);
// extracting a property in that case = get values from maps using property as a key
assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);
// non type safe version
assertThat(maps).extracting("key2").containsExactly(luke, han);
assertThat(maps).extracting("key1").containsExactly(yoda, yoda);
// it works with several keys, extracted values being wrapped in a Tuple
assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));
// unknown keys leads to null (map behavior)
assertThat(maps).extracting("bad key").containsExactly(null, null);P - the type of elements extracted.propertyOrField - the property/field to extract from the Iterable under testextractingType - type to returnIntrospectionError - if no field or property exists with the given name in one of the initial
Iterable's element.public AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> extracting(String... propertiesOrFields)
It allows you to test fields/properties of the Iterable's elements instead of testing the elements themselves, which can be much less work!
The Tuple data corresponds to the extracted values of the given fields/properties, for instance if you ask to extract "id", "name" and "email" then each Tuple data will be composed of id, name and email extracted from the element of the initial Iterable (the Tuple's data order is the same as the given fields/properties order).
Let's take an example to make things clearer:
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify 'name' and 'age' of some TolkienCharacter in fellowshipOfTheRing:
assertThat(fellowshipOfTheRing).extracting("name", "age")
.contains(tuple("Boromir", 37),
tuple("Sam", 38),
tuple("Legolas", 1000));
// extract 'name', 'age' and Race name values:
assertThat(fellowshipOfTheRing).extracting("name", "age", "race.name")
.contains(tuple("Boromir", 37, "Man"),
tuple("Sam", 38, "Hobbit"),
tuple("Legolas", 1000, "Elf"));
A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked
for, if the field does not exist an IntrospectionError is thrown, by default private fields are read but
you can change this with Assertions.setAllowComparingPrivateFields(boolean), trying to read a private field
when it's not allowed leads to an IntrospectionError.
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet, you won't be able to make any assumptions on the extracted values
order.
Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values corresponding to the given keys.
Example:
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee luke = new Employee(2L, new Name("Luke"), 22);
Employee han = new Employee(3L, new Name("Han"), 31);
// build two maps
Map<String, Employee> map1 = new HashMap<>();
map1.put("key1", yoda);
map1.put("key2", luke);
Map<String, Employee> map2 = new HashMap<>();
map2.put("key1", yoda);
map2.put("key2", han);
// instead of a list of objects, we have a list of maps
List<Map<String, Employee>> maps = asList(map1, map2);
// extracting a property in that case = get values from maps using property as a key
assertThat(maps).extracting("key2").containsExactly(luke, han);
assertThat(maps).extracting("key1").containsExactly(yoda, yoda);
// it works with several keys, extracted values being wrapped in a Tuple
assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));
// unknown keys leads to null (map behavior)
assertThat(maps).extracting("bad key").containsExactly(null, null);propertiesOrFields - the properties/fields to extract from the elements of the Iterable under testIntrospectionError - if one of the given name does not match a field or property in one of the initial
Iterable's element.public <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(Function<? super ELEMENT,V> extractor)
It allows to test values from the elements more safely than by using extracting(String), as it
doesn't utilize introspection.
Let's have a look at an example:
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// fellowship has hobbitses, right, my presioussss?
assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getRace).contains(HOBBIT);
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet, you won't be able to make any assumptions on the extracted values order.V - the type of elements extracted.extractor - the object transforming input object to desired onepublic <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> map(Function<? super ELEMENT,V> mapper)
This allows to test values from the elements more safely than by using extracting(String).
Let's have a look at an example:
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// fellowship has hobbitses, right, my precioussss?
assertThat(fellowshipOfTheRing).map(TolkienCharacter::getRace)
.contains(HOBBIT);
Note that the order of mapped values is consistent with the order of the Iterable under test, for example if
it's a HashSet, you won't be able to make any assumptions on the extracted values order.V - the type of elements resulting of the map operation.mapper - the Function transforming input object to desired onepublic <V,EXCEPTION extends Exception> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(ThrowingExtractor<? super ELEMENT,V,EXCEPTION> extractor)
Any checked exception raised in the extractor is rethrown wrapped in a RuntimeException.
It allows to test values from the elements more safely than by using extracting(String), as it
doesn't utilize introspection.
Let's have a look at an example:
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
assertThat(fellowshipOfTheRing).extracting(input -> {
if (input.getAge() < 20) {
throw new Exception("age < 20");
}
return input.getName();
}).contains("Frodo");
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet, you won't be able to make any assumptions on the extracted values
order.EXCEPTION - the exception type of ThrowingExtractorV - the type of elements extracted.extractor - the object transforming input object to desired onepublic <V,EXCEPTION extends Exception> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> map(ThrowingExtractor<? super ELEMENT,V,EXCEPTION> mapper)
Any checked exception raised in the function is rethrown wrapped in a RuntimeException.
This allows to test values from the elements more safely than by using extracting(String).
Let's have a look at an example:
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
assertThat(fellowshipOfTheRing).map(input -> {
if (input.getAge() < 20) {
throw new Exception("age < 20");
}
return input.getName();
}).contains("Frodo");
Note that the order of mapped values is consistent with the order of the Iterable under test, for example if it's a
HashSet, you won't be able to make any assumptions on the extracted values order.EXCEPTION - the exception type of ThrowingExtractorV - the type of elements extracted.mapper - the function transforming input object to desired onepublic <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(Function<? super ELEMENT,? extends Collection<V>> extractor)
Example:
CartoonCharacter bart = new CartoonCharacter("Bart Simpson");
CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");
CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");
CartoonCharacter homer = new CartoonCharacter("Homer Simpson");
homer.getChildren().add(bart);
homer.getChildren().add(lisa);
homer.getChildren().add(maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
List<CartoonCharacter> parents = list(homer, fred);
// check children property which is a List<CartoonCharacter>
assertThat(parents).flatExtracting(CartoonCharacter::getChildren)
.containsOnly(bart, lisa, maggie, pebbles);
The extracted values order is consistent with both the order of the iterable itself as well as the extracted collections.V - the type of extracted elements.extractor - the Function transforming input object to an Iterable of desired onespublic <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatMap(Function<? super ELEMENT,? extends Collection<V>> mapper)
Function and flattens the resulting collections in a
list becoming the object under test.
Example:
CartoonCharacter bart = new CartoonCharacter("Bart Simpson");
CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");
CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");
CartoonCharacter homer = new CartoonCharacter("Homer Simpson");
homer.getChildren().add(bart);
homer.getChildren().add(lisa);
homer.getChildren().add(maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
List<CartoonCharacter> parents = list(homer, fred);
// check children property which is a List<CartoonCharacter>
assertThat(parents).flatMap(CartoonCharacter::getChildren)
.containsOnly(bart, lisa, maggie, pebbles);
The mapped values order is consistent with both the order of the iterable itself as well as the mapped collections.V - the type of mapped elements.mapper - the Function transforming input object to an Iterable of desired onespublic <V,EXCEPTION extends Exception> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION> extractor)
Example:
CartoonCharacter bart = new CartoonCharacter("Bart Simpson");
CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");
CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");
CartoonCharacter homer = new CartoonCharacter("Homer Simpson");
homer.getChildren().add(bart);
homer.getChildren().add(lisa);
homer.getChildren().add(maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
List<CartoonCharacter> parents = list(homer, fred);
// check children property where getChildren() can throw an Exception!
assertThat(parents).flatExtracting(CartoonCharacter::getChildren)
.containsOnly(bart, lisa, maggie, pebbles);
The extracted values order is consistent with both the order of the iterable itself as well as the extracted collections.V - the type of extracted values.EXCEPTION - the exception type of ThrowingExtractorextractor - the object transforming input object to an Iterable of desired onespublic <V,EXCEPTION extends Exception> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatMap(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION> mapper)
Example:
CartoonCharacter bart = new CartoonCharacter("Bart Simpson");
CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");
CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");
CartoonCharacter homer = new CartoonCharacter("Homer Simpson");
homer.getChildren().add(bart);
homer.getChildren().add(lisa);
homer.getChildren().add(maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
List<CartoonCharacter> parents = list(homer, fred);
// check children property where getChildren() can throw an Exception!
assertThat(parents).flatMap(CartoonCharacter::getChildren)
.containsOnly(bart, lisa, maggie, pebbles);
The mapped values order is consistent with both the order of the iterable itself as well as the mapped collections.V - the type of mapped values.EXCEPTION - the exception type of ThrowingExtractormapper - the object transforming input object to an Iterable of desired ones@SafeVarargs public final AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(Function<? super ELEMENT,?>... extractors)
Iterable's element according to the given Functions and
concatenates/flattens them in a list that becomes the instance under test.
If extracted values were not flattened, instead of a simple list like (given 2 extractors):
element1.value1, element1.value2, element2.value1, element2.value2, ...we would get a list of list like:
list(element1.value1, element1.value2), list(element2.value1, element2.value2), ...
Example:
// fellowshipOfTheRing is a List<TolkienCharacter>
// values are extracted in order and flattened: age1, name1, age2, name2, age3 ...
assertThat(fellowshipOfTheRing).flatExtracting(TolkienCharacter::getAge,
TolkienCharacter::getName)
.contains(33 ,"Frodo",
1000, "Legolas",
87, "Aragorn");
The resulting extracted values list is ordered by Iterable's element first and then extracted values,
this is why is in the example age values come before names.extractors - all the extractors to apply on each actual Iterable's elements@SafeVarargs public final AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatMap(Function<? super ELEMENT,?>... mappers)
Iterable's element according to the given Functions
and concatenates/flattens them in a list that becomes the instance under test.
If mapped values were not flattened, instead of a simple list like (given 2 extractors):
element1.value1, element1.value2, element2.value1, element2.value2, ...we would get a list of list like:
list(element1.value1, element1.value2), list(element2.value1, element2.value2), ...
Example:
// fellowshipOfTheRing is a List<TolkienCharacter>
// values are extracted in order and flattened: age1, name1, age2, name2, age3 ...
assertThat(fellowshipOfTheRing).flatMap(TolkienCharacter::getAge,
TolkienCharacter::getName)
.contains(33 ,"Frodo",
1000, "Legolas",
87, "Aragorn");
The resulting mapped values list is ordered by Iterable's element first and then mapped values, this is why is
in the example age values come before names.mappers - all the mappers to apply on each actual Iterable's elementsprotected AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtractingForProxy(Function<? super ELEMENT,?>[] extractors)
@SafeVarargs public final <EXCEPTION extends Exception> AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>... extractors)
Iterable's element according to the given ThrowingExtractors
and concatenates/flattens them in a list that becomes the object under test.
If extracted values were not flattened, instead of a simple list like (given 2 extractors):
element1.value1, element1.value2, element2.value1, element2.value2, ...we would get a list of list like:
list(element1.value1, element1.value2), list(element2.value1, element2.value2), ...
Example:
// fellowshipOfTheRing is a List<TolkienCharacter>
// values are extracted in order and flattened: age1, name1, age2, name2, age3 ...
assertThat(fellowshipOfTheRing).flatExtracting(input -> {
if (input.getAge() < 20) {
throw new Exception("age < 20");
}
return input.getName();
}, input2 -> {
if (input2.getAge() < 20) {
throw new Exception("age < 20");
}
return input2.getAge();
}).contains(33 ,"Frodo",
1000, "Legolas",
87, "Aragorn");
The resulting extracted values list is ordered by Iterable's element first and then extracted values,
this is why is in the example age values come before names.EXCEPTION - the exception type of ThrowingExtractorextractors - all the extractors to apply on each actual Iterable's elements@SafeVarargs public final <EXCEPTION extends Exception> AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatMap(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>... mappers)
Iterable's element according to the given ThrowingExtractors and
concatenates/flattens them in a list that becomes the object under test.
If mapped values were not flattened, instead of a simple list like (given 2 mappers):
element1.value1, element1.value2, element2.value1, element2.value2, ...we would get a list of list like:
list(element1.value1, element1.value2), list(element2.value1, element2.value2), ...
Example:
// fellowshipOfTheRing is a List<TolkienCharacter>
// values are extracted in order and flattened: age1, name1, age2, name2, age3 ...
assertThat(fellowshipOfTheRing).flatMap(input -> {
if (input.getAge() < 20) {
throw new Exception("age < 20");
}
return input.getName();
}, input2 -> {
if (input2.getAge() < 20) {
throw new Exception("age < 20");
}
return input2.getAge();
}).contains(33 ,"Frodo",
1000, "Legolas",
87, "Aragorn");
The resulting mapped values list is ordered by Iterable's element first and then mapped values, this is why is in
the example age values come before names.EXCEPTION - the exception type of ThrowingExtractormappers - all the mappers to apply on each actual Iterable's elementspublic AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(String fieldOrPropertyName)
This allows testing the elements extracted values that are iterables or arrays.
For example:
CartoonCharacter bart = new CartoonCharacter("Bart Simpson");
CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");
CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");
CartoonCharacter homer = new CartoonCharacter("Homer Simpson");
homer.getChildren().add(bart);
homer.getChildren().add(lisa);
homer.getChildren().add(maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
List<CartoonCharacter> parents = list(homer, fred);
// check children which is a List<CartoonCharacter>
assertThat(parents).flatExtracting("children")
.containsOnly(bart, lisa, maggie, pebbles);
The order of extracted values is consisted with both the order of the iterable itself as well as the extracted collections.fieldOrPropertyName - the object transforming input object to an Iterable of desired onesIllegalArgumentException - if one of the extracted property value was not an array or an iterable.@SafeVarargs public final AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> extracting(Function<? super ELEMENT,?>... extractors)
Functions to extract the values from the Iterable's elements into a new Iterable
composed of Tuples (a simple data structure containing the extracted values), this new Iterable becoming the
object under test.
It allows you to test values from the Iterable's elements instead of testing the elements themselves, which sometimes can be
much less work!
The Tuple data correspond to the extracted values from the Iterable's elements, for instance if you pass functions
extracting "id", "name" and "email" values then each Tuple data will be composed of an id, a name and an email
extracted from the element of the initial Iterable (the Tuple's data order is the same as the given functions order).
Let's take a look at an example to make things clearer:
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify 'name', 'age' and Race of some TolkienCharacter in fellowshipOfTheRing:
assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getName,
character -> character.getAge(),
TolkienCharacter::getRace)
.containsOnly(tuple("Frodo", 33, HOBBIT),
tuple("Sam", 38, HOBBIT),
tuple("Gandalf", 2020, MAIA),
tuple("Legolas", 1000, ELF),
tuple("Pippin", 28, HOBBIT),
tuple("Gimli", 139, DWARF),
tuple("Aragorn", 87, MAN),
tuple("Boromir", 37, MAN));
You can use lambda expression or a method reference to extract the expected values.
Use Tuple.tuple(Object...) to initialize the expected values.
Note that the order of the extracted tuples list is consistent with the iteration order of the Iterable under test,
for example if it's a HashSet, you won't be able to make any assumptions on the extracted tuples order.
extractors - the extractor functions to extract a value from an element of the Iterable under test.protected AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> extractingForProxy(Function<? super ELEMENT,?>[] extractors)
@SafeVarargs public final AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> map(Function<? super ELEMENT,?>... mappers)
Functions to map the Iterable's elements into a List of Tuples
(a simple data structure containing the mapped values), this new list becoming the object under test.
This allows you to test values from the Iterable's elements instead of testing the elements themselves, which
sometimes can be much less work!
The Tuple data correspond to the extracted values from the Iterable's elements, for instance if you pass functions
mapping "id", "name" and "email" values then each Tuple data will be composed of an id, a name and an email
mapped from the element of the initial Iterable (the Tuple's data order is the same as the given functions order).
Let's take a look at an example to make things clearer:
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify 'name', 'age' and Race of some TolkienCharacter in fellowshipOfTheRing:
assertThat(fellowshipOfTheRing).map(TolkienCharacter::getName,
character -> character.getAge(),
TolkienCharacter::getRace)
.containsOnly(tuple("Frodo", 33, HOBBIT),
tuple("Sam", 38, HOBBIT),
tuple("Gandalf", 2020, MAIA),
tuple("Legolas", 1000, ELF),
tuple("Pippin", 28, HOBBIT),
tuple("Gimli", 139, DWARF),
tuple("Aragorn", 87, MAN),
tuple("Boromir", 37, MAN));
You can use lambda expression or a method reference to extract the expected values.
Use Tuple.tuple(Object...) to initialize the expected values.
Note that the order of the extracted tuples list is consistent with the iteration order of the Iterable under test,
for example if it's a HashSet, you won't be able to make any assumptions on the extracted tuples order.
mappers - the mapper functions to extract a value from an element of the Iterable under test.public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(String... fieldOrPropertyNames)
Iterable's element and
flatten the extracted values in a list that is used as the new object under test.
Given 2 properties, if the extracted values were not flattened, instead having a simple list like:
element1.value1, element1.value2, element2.value1, element2.value2, ...... we would get a list of list:
list(element1.value1, element1.value2), list(element2.value1, element2.value2), ...
Example:
// fellowshipOfTheRing is a List<TolkienCharacter>
// values are extracted in order and flattened: age1, name1, age2, name2, age3 ...
assertThat(fellowshipOfTheRing).flatExtracting("age", "name")
.contains(33 ,"Frodo",
1000, "Legolas",
87, "Aragorn");fieldOrPropertyNames - the field and/or property names to extract from each actual Iterable's elementIllegalArgumentException - if fieldOrPropertyNames vararg is null or emptypublic SELF containsExactlyElementsOf(Iterable<? extends ELEMENT> iterable)
ObjectEnumerableAssert.containsExactly(Object...) but handle the Iterable to array conversion : verifies that
actual contains exactly the elements of the given iterable and nothing else in the same order.
Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass
assertThat(elvesRings).containsExactlyElementsOf(newLinkedList(vilya, nenya, narya));
// assertion will fail as actual and expected order differ
assertThat(elvesRings).containsExactlyElementsOf(newLinkedList(nenya, vilya, narya));
If you want to directly specify the elements to check, use containsExactly(Object...) instead.
containsExactlyElementsOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>iterable - the given Iterable we will get elements from.this assertion object.@Deprecated public SELF containsOnlyElementsOf(Iterable<? extends ELEMENT> iterable)
ObjectEnumerableAssert.containsOnly(Object[]) : verifies that actual contains all the elements of the given
iterable and nothing else, in any order and ignoring duplicates (i.e. once a value is found, its duplicates are also considered found).
This assertion has been deprecated because its name is confusing, users were expecting it to behave like ObjectEnumerableAssert.isSubsetOf(Iterable).
For example this assertion fails when users expected it to pass:
Iterable<Ring> rings = list(nenya, vilya);
// assertion fails because narya is not in rings, confusing!
assertThat(rings).containsOnlyElementsOf(list(nenya, vilya, narya));
Use ObjectEnumerableAssert.isSubsetOf(Iterable) to check that actual is a subset of given iterable, or if you need to same assertion semantics use ObjectEnumerableAssert.hasSameElementsAs(Iterable).
Examples:
Iterable<Ring> rings = newArrayList(nenya, vilya);
// assertion will pass
assertThat(rings).containsOnlyElementsOf(list(nenya, vilya))
.containsOnlyElementsOf(list(nenya, nenya, vilya, vilya));
assertThat(list(nenya, nenya, vilya, vilya)).containsOnlyElementsOf(rings);
// assertion will fail as actual does not contain narya
assertThat(rings).containsOnlyElementsOf(list(nenya, vilya, narya));
// assertion will fail as actual contains nenya
assertThat(rings).containsOnlyElementsOf(list(vilya));
If you want to directly specify the elements to check, use containsOnly(Object...) instead.
containsOnlyElementsOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>iterable - the given Iterable we will get elements from.this assertion object.public SELF containsOnlyOnceElementsOf(Iterable<? extends ELEMENT> iterable)
ObjectEnumerableAssert.containsOnlyOnce(Object...) : verifies that the actual group contains the elements of
the given iterable only once.
Examples :
// assertions will pass
assertThat(list("winter", "is", "coming")).containsOnlyOnceElementsOf(list("winter"))
.containsOnlyOnceElementsOf(list("coming", "winter"));
// assertions will fail
assertThat(list("winter", "is", "coming")).containsOnlyOnceElementsOf(list("Lannister"));
assertThat(list("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnceElementsOf(list("Stark"));
assertThat(list("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnceElementsOf(list("Stark", "Lannister", "Arya"));
If you want to directly specify the elements to check with, use ObjectEnumerableAssert.containsOnlyOnce(Object...) instead.
containsOnlyOnceElementsOf in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>iterable - the given Iterable we will get elements from.this assertion object.public SELF hasSameElementsAs(Iterable<? extends ELEMENT> iterable)
Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass:
assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya, vilya))
.hasSameElementsAs(newArrayList(nenya, narya, vilya, nenya));
// assertions will fail:
assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya));
assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya, vilya, oneRing));hasSameElementsAs in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>iterable - the Iterable whose elements we expect to be present@Deprecated public <T> SELF usingComparatorForElementFieldsWithNames(Comparator<T> comparator, String... elementPropertyOrFieldNames)
usingFieldByFieldElementComparator() which is deprecated in favor of
usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) or usingRecursiveComparison().
When using usingRecursiveComparison() the equivalent is:
RecursiveComparisonAssert.withEqualsForFields(java.util.function.BiPredicate, String...)RecursiveComparisonAssert.withComparatorForFields(Comparator, String...)
and when using RecursiveComparisonConfiguration:
RecursiveComparisonConfiguration.Builder#withEqualsForFields(java.util.function.BiPredicate, String...)RecursiveComparisonConfiguration.Builder#withComparatorForFields(Comparator, String...)Allows to set a comparator to compare properties or fields of elements with the given names. A typical usage is for comparing fields of numeric type at a given precision.
To be used, comparators need to be specified by this method before calling any of:
usingFieldByFieldElementComparator()usingElementComparatorOnFields(java.lang.String...)usingElementComparatorIgnoringFields(java.lang.String...)
Comparators specified by this method have precedence over comparators specified by
usingComparatorForElementFieldsWithType.
Example:
public class TolkienCharacter {
private String name;
private double height;
// constructor omitted
}
TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2);
TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3);
TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9);
Comparator<Double> closeEnough = new Comparator<Double>() {
double precision = 0.5;
public int compare(Double d1, Double d2) {
return Math.abs(d1 - d2) <= precision ? 0 : 1;
}
};
// assertions will pass
assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingFieldByFieldElementComparator()
.contains(tallerFrodo);
assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingElementComparatorOnFields("height")
.contains(tallerFrodo);
assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingElementComparatorIgnoringFields("name")
.contains(tallerFrodo);
assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingRecursiveFieldByFieldElementComparator()
.contains(tallerFrodo);
// assertion will fail
assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingFieldByFieldElementComparator()
.containsExactly(reallyTallFrodo);T - the type of elements to compare.comparator - the Comparator to useelementPropertyOrFieldNames - the names of the properties and/or fields of the elements the comparator should be used forthis assertions object@Deprecated public <T> SELF usingComparatorForElementFieldsWithType(Comparator<T> comparator, Class<T> type)
usingFieldByFieldElementComparator() which is deprecated in favor of
usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) or usingRecursiveComparison().
When using usingRecursiveComparison() the equivalent is:
RecursiveComparisonAssert.withEqualsForType(java.util.function.BiPredicate, Class)RecursiveComparisonAssert.withComparatorForType(Comparator, Class)
and when using RecursiveComparisonConfiguration:
RecursiveComparisonConfiguration.Builder#withEqualsForType(java.util.function.BiPredicate, Class)RecursiveComparisonConfiguration.Builder#withComparatorForType(Comparator, Class)Allows to set a specific comparator to compare properties or fields of elements with the given type. A typical usage is for comparing fields of numeric type at a given precision.
To be used, comparators need to be specified by this method before calling any of:
usingFieldByFieldElementComparator()usingElementComparatorOnFields(java.lang.String...)usingElementComparatorIgnoringFields(java.lang.String...)
Comparators specified by usingComparatorForElementFieldsWithNames
have precedence over comparators specified by this method.
Example:
public class TolkienCharacter {
private String name;
private double height;
// constructor omitted
}
TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2);
TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3);
TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9);
Comparator<Double> closeEnough = new Comparator<Double>() {
double precision = 0.5;
public int compare(Double d1, Double d2) {
return Math.abs(d1 - d2) <= precision ? 0 : 1;
}
};
// assertions will pass
assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingFieldByFieldElementComparator()
.contains(tallerFrodo);
assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingElementComparatorOnFields("height")
.contains(tallerFrodo);
assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingElementComparatorIgnoringFields("name")
.contains(tallerFrodo);
assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingRecursiveFieldByFieldElementComparator()
.contains(tallerFrodo);
// assertion will fail
assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingFieldByFieldElementComparator()
.contains(reallyTallFrodo);T - the type of elements to compare.comparator - the Comparator to usetype - the Class of the type of the element fields the comparator should be used forthis assertions objectpublic <T> SELF usingComparatorForType(Comparator<T> comparator, Class<T> type)
usingComparatorForElementFieldsWithType(java.util.Comparator<T>, java.lang.Class<T>) by applying comparator specified for given type
to elements themselves, not only to their fields.
Usage of this method affects comparators set by next methods:
usingFieldByFieldElementComparator()usingElementComparatorOnFields(java.lang.String...)usingElementComparatorIgnoringFields(java.lang.String...)Example:
// assertion will pass
assertThat(asList("some", new BigDecimal("4.2")))
.usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class)
.contains(new BigDecimal("4.20"));
T - the type of elements to compare.comparator - the Comparator to usetype - the Class of the type of the element or element fields the comparator should be used forthis assertions object@Deprecated public SELF usingFieldByFieldElementComparator()
usingRecursiveFieldByFieldElementComparator()
or usingRecursiveComparison() instead to perform a true recursive comparison.
Use field/property by field/property comparison (including inherited fields/properties) instead of relying on
actual type A equals method to compare group elements for incoming assertion checks. Private fields
are included but this can be disabled using Assertions.setAllowExtractingPrivateFields(boolean).
This can be handy if equals method of the objects to compare does not suit you.
Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared
to the other field/property using its equals method.
You can specify a custom comparator per name or type of element field with
usingComparatorForElementFieldsWithNames(Comparator, String...)
and usingComparatorForElementFieldsWithType(Comparator, Class).
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);
// Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references
assertThat(newArrayList(frodo)).contains(frodoClone);
// frodo and frodoClone are equals when doing a field by field comparison.
assertThat(newArrayList(frodo)).usingFieldByFieldElementComparator().contains(frodoClone);this assertion object.public SELF usingRecursiveFieldByFieldElementComparator()
usingRecursiveComparison() but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists).
This method uses the default RecursiveComparisonConfiguration, if you need to customize it use usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) instead.
Breaking change: since 3.20.0 the comparison won't use any comparators set with:
usingComparatorForType(Comparator, Class)withTypeComparators(TypeComparators)usingComparatorForElementFieldsWithType(Comparator, Class)withComparatorsForElementPropertyOrFieldTypes(TypeComparators)usingComparatorForElementFieldsWithNames(Comparator, String...)withComparatorsForElementPropertyOrFieldNames(Map)
These features (and many more) are provided through usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) with a customized RecursiveComparisonConfiguration where there methods are called:
registerComparatorForType(Comparator, Class) / withComparatorForType(Comparator, Class) (using RecursiveComparisonConfiguration.Builder)registerEqualsForType(BiPredicate, Class) / withComparatorForType(Comparator, Class) (using RecursiveComparisonConfiguration.Builder)registerComparatorForFields(Comparator comparator, String... fields) / withComparatorForField(Comparator comparator, String... fields) (using RecursiveComparisonConfiguration.Builder)
There are differences between this approach and usingRecursiveComparison():
RecursiveComparisonAssert, you can chain any iterable assertions after this method.usingComparatorForType(Comparator, Class) will be used, you need to register them in the configuration object.RecursiveComparisonAssert.isEqualTo(Object) which shows the field differences.
This last point makes sense, take the contains(Object...) assertion, it would not be relevant to report the differences of all the iterable's elements differing from the values to look for.
Example:
public class Person {
String name;
boolean hasPhd;
}
public class Doctor {
String name;
boolean hasPhd;
}
Doctor drSheldon = new Doctor("Sheldon Cooper", true);
Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
Doctor drRaj = new Doctor("Raj Koothrappali", true);
Person sheldon = new Person("Sheldon Cooper", true);
Person leonard = new Person("Leonard Hofstadter", true);
Person raj = new Person("Raj Koothrappali", true);
Person howard = new Person("Howard Wolowitz", true);
List<Doctor> doctors = list(drSheldon, drLeonard, drRaj);
List<Person> people = list(sheldon, leonard, raj);
// assertion succeeds as both lists contains equivalent items in order.
assertThat(doctors).usingRecursiveFieldByFieldElementComparator()
.contains(sheldon);
// assertion fails because leonard names are different.
leonard.setName("Leonard Ofstater");
assertThat(doctors).usingRecursiveFieldByFieldElementComparator()
.contains(leonard);
// assertion fails because howard is missing and leonard is not expected.
people = list(howard, sheldon, raj)
assertThat(doctors).usingRecursiveFieldByFieldElementComparator()
.contains(howard);
Another point worth mentioning: elements order does matter if the expected iterable is ordered, for example comparing a Set<Person> to a List<Person> fails as List is ordered and Set is not.
The ordering can be ignored by calling ignoringCollectionOrder allowing ordered/unordered iterable comparison, note that ignoringCollectionOrder is applied recursively on any nested iterable fields, if this behavior is too generic,
use the more fine grained ignoringCollectionOrderInFields or
ignoringCollectionOrderInFieldsMatchingRegexes.
this assertion object.RecursiveComparisonConfiguration,
usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)public SELF usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration configuration)
usingRecursiveComparison() but contrary to the latter you can chain any iterable assertions after this method (this is why this method exists).
The given RecursiveComparisonConfiguration is used to tweak the comparison behavior, for example by ignoring collection order.
Warning: the comparison won't use any comparators set with:
usingComparatorForType(Comparator, Class)withTypeComparators(TypeComparators)usingComparatorForElementFieldsWithType(Comparator, Class)withComparatorsForElementPropertyOrFieldTypes(TypeComparators)usingComparatorForElementFieldsWithNames(Comparator, String...)withComparatorsForElementPropertyOrFieldNames(Map)
These features (and many more) are provided through RecursiveComparisonConfiguration with:
registerComparatorForType(Comparator, Class) / withComparatorForType(Comparator, Class) (using RecursiveComparisonConfiguration.Builder)registerEqualsForType(BiPredicate, Class) / withComparatorForType(Comparator, Class) (using RecursiveComparisonConfiguration.Builder)registerComparatorForFields(Comparator comparator, String... fields) / withComparatorForField(Comparator comparator, String... fields) (using RecursiveComparisonConfiguration.Builder)
RecursiveComparisonConfiguration exposes a builder to ease setting the comparison behaviour,
call RecursiveComparisonConfiguration.builder() to start building your configuration.
There are differences between this approach and usingRecursiveComparison():
RecursiveComparisonAssert, you can chain any iterable assertions after this method.usingComparatorForType(Comparator, Class) will be used, you need to register them in the configuration object.RecursiveComparisonAssert.isEqualTo(Object) which shows the field differences.
This last point makes sense, take the contains(Object...) assertion, it would not be relevant to report the differences of all the iterable's elements differing from the values to look for.
Example:
public class Person {
String name;
boolean hasPhd;
}
public class Doctor {
String name;
boolean hasPhd;
}
Doctor drSheldon = new Doctor("Sheldon Cooper", true);
Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
Doctor drRaj = new Doctor("Raj Koothrappali", true);
Person sheldon = new Person("Sheldon Cooper", false);
Person leonard = new Person("Leonard Hofstadter", false);
Person raj = new Person("Raj Koothrappali", false);
Person howard = new Person("Howard Wolowitz", false);
List<Doctor> doctors = list(drSheldon, drLeonard, drRaj);
List<Person> people = list(sheldon, leonard, raj);
RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
.withIgnoredFields("hasPhd");
// assertion succeeds as both lists contains equivalent items in order.
assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
.contains(sheldon);
// assertion fails because leonard names are different.
leonard.setName("Leonard Ofstater");
assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
.contains(leonard);
// assertion fails because howard is missing and leonard is not expected.
people = list(howard, sheldon, raj)
assertThat(doctors).usingRecursiveFieldByFieldElementComparator(configuration)
.contains(howard);
A detailed documentation for the recursive comparison is available here: https://assertj.github.io/doc/#assertj-core-recursive-comparison.
The default recursive comparison behavior is configured as follows:
List<Person> and a LinkedHashSet<PersonDto>.withStrictTypeChecking.java.lang.Double: DoubleComparator with precision of 1.0E-15java.lang.Float: FloatComparator with precision of 1.0E-6
Another point worth mentioning: elements order does matter if the expected iterable is ordered, for example comparing a Set<Person> to a List<Person> fails as List is ordered and Set is not.
The ordering can be ignored by calling ignoringCollectionOrder allowing ordered/unordered iterable comparison, note that ignoringCollectionOrder is applied recursively on any nested iterable fields, if this behavior is too generic,
use the more fine grained ignoringCollectionOrderInFields or
ignoringCollectionOrderInFieldsMatchingRegexes.
configuration - the recursive comparison configuration.this assertion object.RecursiveComparisonConfigurationpublic RecursiveComparisonAssert<?> usingRecursiveComparison()
RecursiveComparisonAssert,
There are differences between this approach and usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration):
RecursiveComparisonAssert assertions (basically isEqualTo) and (basically isNotEqualTo), no iterable assertions.isEqualTo assertion error will report all field differences (very detailed).usingComparatorForType(Comparator, Class) will be used, you need to register them in chained call like RecursiveComparisonAssert.withComparatorForType(Comparator, Class).
If you need to chain iterable assertions using recursive comparisons call usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) instead.
Example:
public class Person {
String name;
boolean hasPhd;
}
public class Doctor {
String name;
boolean hasPhd;
}
Doctor drSheldon = new Doctor("Sheldon Cooper", true);
Doctor drLeonard = new Doctor("Leonard Hofstadter", true);
Doctor drRaj = new Doctor("Raj Koothrappali", true);
Person sheldon = new Person("Sheldon Cooper", true);
Person leonard = new Person("Leonard Hofstadter", true);
Person raj = new Person("Raj Koothrappali", true);
Person howard = new Person("Howard Wolowitz", false);
List<Doctor> doctors = Arrays.asList(drSheldon, drLeonard, drRaj);
List<Person> people = Arrays.asList(sheldon, leonard, raj);
// assertion succeeds as both lists contains equivalent items in order.
assertThat(doctors).usingRecursiveComparison()
.isEqualTo(people);
// assertion fails because leonard names are different.
leonard.setName("Leonard Ofstater");
assertThat(doctors).usingRecursiveComparison()
.isEqualTo(people);
// assertion fails because howard is missing and leonard is not expected.
people = Arrays.asList(howard, sheldon, raj)
assertThat(doctors).usingRecursiveComparison()
.isEqualTo(people);
A detailed documentation for the recursive comparison is available here: https://assertj.github.io/doc/#assertj-core-recursive-comparison.
The default recursive comparison behavior is configured as follows:
List<Person> and a LinkedHashSet<PersonDto>.withStrictTypeChecking.java.lang.Double: DoubleComparator with precision of 1.0E-15java.lang.Float: FloatComparator with precision of 1.0E-6
Another point worth mentioning: elements order does matter if the expected iterable is ordered, for example comparing a Set<Person> to a List<Person> fails as List is ordered and Set is not.
The ordering can be ignored by calling ignoringCollectionOrder allowing ordered/unordered iterable comparison, note that ignoringCollectionOrder is applied recursively on any nested iterable fields, if this behavior is too generic,
use the more fine grained ignoringCollectionOrderInFields or
ignoringCollectionOrderInFieldsMatchingRegexes.
At the moment, only `isEqualTo` can be chained after this method but there are plans to provide assertions.
usingRecursiveComparison in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>RecursiveComparisonAssert instanceRecursiveComparisonConfigurationpublic RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration)
usingRecursiveComparison() but allows to specify your own RecursiveComparisonConfiguration.
Another difference is that any comparators previously registered with usingComparatorForType(Comparator, Class) will be used in the comparison.
usingRecursiveComparison in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>recursiveComparisonConfiguration - the RecursiveComparisonConfiguration used in the chained isEqualTo assertion.RecursiveComparisonAssert instance built with the given RecursiveComparisonConfiguration.@Deprecated public SELF usingElementComparatorOnFields(String... fields)
usingRecursiveFieldByFieldElementComparatorOnFields(String...) instead.
Use field/property by field/property comparison on the given fields/properties only (including inherited
fields/properties) instead of relying on actual type A equals method to compare group elements for
incoming assertion checks. Private fields are included but this can be disabled using
Assertions.setAllowExtractingPrivateFields(boolean).
This can be handy if equals method of the objects to compare does not suit you.
You can specify a custom comparator per name or type of element field with
usingComparatorForElementFieldsWithNames(Comparator, String...)
and usingComparatorForElementFieldsWithType(Comparator, Class).
Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared
to the other field/property using its equals method.
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);
// frodo and sam both are hobbits, so they are equals when comparing only race
assertThat(newArrayList(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK
// ... but not when comparing both name and race
assertThat(newArrayList(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAILfields - the fields/properties to compare using element comparatorsthis assertion object.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration),
https://assertj.github.io/doc/#assertj-core-recursive-comparisonpublic SELF usingRecursiveFieldByFieldElementComparatorOnFields(String... fields)
equals method.
This is handy when the element equals method is not overridden or implemented as you expect.
Nested fields are supported and are expressed like: name.first
The comparison is recursive: elements are compared field by field, if a field type has fields they are also compared field by field (and so on).
Example:
Player derrickRose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
derrickRose.nickname = new Name("Crazy", "Dunks");
Player jalenRose = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
jalenRose.nickname = new Name("Crazy", "Defense");
// assertion succeeds as all compared fields match
assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name.last", "team", "nickname.first")
.contains(jalenRose);
// assertion fails, name.first values differ
assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name")
.contains(jalenRose);
This method is actually a shortcut of usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)
with a configuration comparing only the given fields, the previous example can be written as:
RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
.withComparedFields("name.last", "team", "nickname.first")
.build();
assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparator(configuration)
.contains(jalenRose);
The recursive comparison is documented here: https://assertj.github.io/doc/#assertj-core-recursive-comparison
fields - the field names to exclude in the elements comparison.this assertion object.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration),
https://assertj.github.io/doc/#assertj-core-recursive-comparisonprotected SELF usingComparisonStrategy(ComparisonStrategy comparisonStrategy)
@Deprecated public SELF usingElementComparatorIgnoringFields(String... fields)
usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...) instead.
Use field/property by field/property comparison on all fields/properties except the given ones (including inherited
fields/properties) instead of relying on actual type A equals method to compare group elements for
incoming assertion checks. Private fields are included but this can be disabled using
Assertions.setAllowExtractingPrivateFields(boolean).
This can be handy if equals method of the objects to compare does not suit you.
You can specify a custom comparator per name or type of element field with
usingComparatorForElementFieldsWithNames(Comparator, String...)
and usingComparatorForElementFieldsWithType(Comparator, Class).
Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared
to the other field/property using its equals method.
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);
// frodo and sam both are hobbits, so they are equals when comparing only race (i.e. ignoring all other fields)
assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK
// ... but not when comparing both name and race
assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAILfields - the field names to exclude in the elements comparison.this assertion object.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration),
https://assertj.github.io/doc/#assertj-core-recursive-comparisonpublic SELF usingRecursiveFieldByFieldElementComparatorIgnoringFields(String... fields)
equals method.
This is handy when the element equals method is not overridden or implemented as you expect.
Nested fields are supported and are expressed like: name.first
The comparison is recursive: elements are compared field by field, if a field type has fields they are also compared field by field (and so on).
Example:
Player derrickRose = new Player(new Name("Derrick", "Rose"), "Chicago Bulls");
derrickRose.nickname = new Name("Crazy", "Dunks");
Player jalenRose = new Player(new Name("Jalen", "Rose"), "Chicago Bulls");
jalenRose.nickname = new Name("Crazy", "Defense");
// assertion succeeds
assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last")
.contains(jalenRose);
// assertion fails, names are ignored but nicknames are not and nickname.last values differ
assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name")
.contains(jalenRose);
This method is actually a shortcut of usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)
with a configuration ignoring the given fields, the previous example can be written as:
RecursiveComparisonConfiguration configuration = RecursiveComparisonConfiguration.builder()
.withIgnoredFields("name.first", "nickname.last")
.build();
assertThat(list(derrickRose)).usingRecursiveFieldByFieldElementComparator(configuration)
.contains(jalenRose);
The recursive comparison is documented here: https://assertj.github.io/doc/#assertj-core-recursive-comparison
fields - the field names to exclude in the elements comparison.this assertion object.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration),
https://assertj.github.io/doc/#assertj-core-recursive-comparisonpublic SELF inHexadecimal()
It can be useful to better understand what the error was with a more meaningful error message.
Example
final List<Byte> bytes = newArrayList((byte) 0x10, (byte) 0x20);
With standard error message:
assertThat(bytes).contains((byte) 0x30);
Expecting:
<[16, 32]>
to contain:
<[48]>
but could not find:
<[48]>
With Hexadecimal error message:
assertThat(bytes).inHexadecimal().contains((byte) 0x30);
Expecting:
<[0x10, 0x20]>
to contain:
<[0x30]>
but could not find:
<[0x30]>inHexadecimal in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>this assertion object.public SELF inBinary()
Example:
final List<Byte> bytes = newArrayList((byte) 0x10, (byte) 0x20);
With standard error message:
assertThat(bytes).contains((byte) 0x30);
Expecting:
<[16, 32]>
to contain:
<[48]>
but could not find:
<[48]>
With binary error message:
assertThat(bytes).inBinary().contains((byte) 0x30);
Expecting:
<[0b00010000, 0b00100000]>
to contain:
<[0b00110000]>
but could not find:
<[0b00110000]>inBinary in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>this assertion object.public SELF filteredOn(String propertyOrFieldName, Object expectedValue)
expectedValue, the
property/field is specified by propertyOrFieldName parameter.
The filter first tries to get the value from a property (named propertyOrFieldName), if no such property
exists it tries to read the value from a field. Reading private fields is supported by default, this can be
globally disabled by calling Assertions.setAllowExtractingPrivateFields(false).
When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check all employees 800 years old (yes, special employees):
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
Employee noname = new Employee(4L, null, 50);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
assertThat(employees).filteredOn("age", 800)
.containsOnly(yoda, obiwan);
Nested properties/fields are supported:
// Name is bean class with 'first' and 'last' String properties
// name is null for noname => it does not match the filter on "name.first"
assertThat(employees).filteredOn("name.first", "Luke")
.containsOnly(luke);
assertThat(employees).filteredOn("name.last", "Vader")
.isEmpty();
If you want to filter on null value, use filteredOnNull(String) as Java will resolve the call to
filteredOn(String, FilterOperator) instead of this method.
An IntrospectionError is thrown if the given propertyOrFieldName can't be found in one of the iterable
elements.
You can chain filters:
// fellowshipOfTheRing is a list of TolkienCharacter having race and name fields
// 'not' filter is statically imported from Assertions.not
assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")
.filteredOn("name", not("Boromir"))
.containsOnly(aragorn);
If you need more complex filter, use filteredOn(Predicate) or filteredOn(Condition).propertyOrFieldName - the name of the property or field to readexpectedValue - the value to compare element's property or field withIllegalArgumentException - if the given propertyOrFieldName is null or empty.IntrospectionError - if the given propertyOrFieldName can't be found in one of the iterable elements.public SELF filteredOnNull(String propertyOrFieldName)
propertyOrFieldName is null.
The filter first tries to get the value from a property (named propertyOrFieldName), if no such property
exists it tries to read the value from a field. Reading private fields is supported by default, this can be
globally disabled by calling Assertions.setAllowExtractingPrivateFields(false).
When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check all employees 800 years old (yes, special employees):
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
Employee noname = new Employee(4L, null, 50);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
assertThat(employees).filteredOnNull("name")
.containsOnly(noname);
Nested properties/fields are supported:
// Name is bean class with 'first' and 'last' String properties
assertThat(employees).filteredOnNull("name.last")
.containsOnly(yoda, obiwan, noname);
An IntrospectionError is thrown if the given propertyOrFieldName can't be found in one of the iterable
elements.
If you need more complex filter, use filteredOn(Predicate) or filteredOn(Condition).
propertyOrFieldName - the name of the property or field to readIntrospectionError - if the given propertyOrFieldName can't be found in one of the iterable elements.public SELF filteredOn(String propertyOrFieldName, FilterOperator<?> filterOperator)
FilterOperator, the property/field is specified by propertyOrFieldName parameter.
The existing filters are:
Whatever filter is applied, it first tries to get the value from a property (named propertyOrFieldName), if
no such property exists it tries to read the value from a field. Reading private fields is supported by default,
this can be globally disabled by calling Assertions.setAllowExtractingPrivateFields(false).
When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check stuff on some special employees:
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
// 'not' filter is statically imported from Assertions.not
assertThat(employees).filteredOn("age", not(800))
.containsOnly(luke);
// 'in' filter is statically imported from Assertions.in
// Name is bean class with 'first' and 'last' String properties
assertThat(employees).filteredOn("name.first", in("Yoda", "Luke"))
.containsOnly(yoda, luke);
// 'notIn' filter is statically imported from Assertions.notIn
assertThat(employees).filteredOn("name.first", notIn("Yoda", "Luke"))
.containsOnly(obiwan);
An IntrospectionError is thrown if the given propertyOrFieldName can't be found in one of the iterable
elements.
Note that combining filter operators is not supported, thus the following code is not correct:
// Combining filter operators like not(in(800)) is NOT supported
// -> throws UnsupportedOperationException
assertThat(employees).filteredOn("age", not(in(800)))
.contains(luke);
You can chain filters:
// fellowshipOfTheRing is a list of TolkienCharacter having race and name fields
// 'not' filter is statically imported from Assertions.not
assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")
.filteredOn("name", not("Boromir"))
.containsOnly(aragorn);
If you need more complex filter, use filteredOn(Predicate) or filteredOn(Condition).propertyOrFieldName - the name of the property or field to readfilterOperator - the filter operator to applyIllegalArgumentException - if the given propertyOrFieldName is null or empty.public SELF filteredOn(Condition<? super ELEMENT> condition)
Condition.
If you prefer Predicate over Condition, use filteredOn(Predicate).
Example: check old employees whose age > 100:
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
Employee noname = new Employee(4L, null, 50);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
// old employee condition, "old employees" describes the condition in error message
// you just have to implement 'matches' method
Condition<Employee> oldEmployees = new Condition<Employee>("old employees") {
@Override
public boolean matches(Employee employee) {
return employee.getAge() > 100;
}
};
}
assertThat(employees).filteredOn(oldEmployees)
.containsOnly(yoda, obiwan);
You can combine Condition with condition operator like Not:
// 'not' filter is statically imported from Assertions.not
assertThat(employees).filteredOn(not(oldEmployees))
.contains(luke, noname);condition - the filter condition / predicateIllegalArgumentException - if the given condition is null.public <T> SELF filteredOn(Function<? super ELEMENT,T> function, T expectedValue)
function is equal to expectedValue.
It allows to filter elements more safely than by using filteredOn(String, Object) as it doesn't utilize introspection.
As an example, let's check all employees 800 years old (yes, special employees):
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
Employee noname = new Employee(4L, null, 50);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
assertThat(employees).filteredOn(Employee::getAge, 800)
.containsOnly(yoda, obiwan);
assertThat(employees).filteredOn(e -> e.getName(), null)
.containsOnly(noname);
If you need more complex filter, use filteredOn(Predicate) or filteredOn(Condition).T - result type of the filter functionfunction - the filter functionexpectedValue - the expected value of the filter functionIllegalArgumentException - if the given function is null.public SELF filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions)
Consumer.
Example: check young hobbits whose age < 34:
TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter merry = new TolkienCharacter("Merry", 36, HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);
List<TolkienCharacter> hobbits = list(frodo, sam, merry, pippin);
assertThat(hobbits).filteredOnAssertions(hobbit -> assertThat(hobbit.age).isLessThan(34))
.containsOnly(frodo, pippin);elementAssertions - containing AssertJ assertions to filter onIllegalArgumentException - if the given Consumer is null.public SELF filteredOnAssertions(ThrowingConsumer<? super ELEMENT> elementAssertions)
ThrowingConsumer.
This is the same assertion as filteredOnAssertions(Consumer) but the given consumer can throw checked exceptions.
More precisely, RuntimeException and AssertionError are rethrown as they are and Throwable wrapped in a RuntimeException.
Example: check young hobbits whose age < 34:
TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT);
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter merry = new TolkienCharacter("Merry", 36, HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);
List<TolkienCharacter> hobbits = list(frodo, sam, merry, pippin);
// the code would compile even if getAge() threw a checked exception
assertThat(hobbits).filteredOnAssertions(hobbit -> assertThat(hobbit.getAge()).isLessThan(34))
.containsOnly(frodo, pippin);elementAssertions - containing AssertJ assertions to filter onIllegalArgumentException - if the given ThrowingConsumer is null.public ELEMENT_ASSERT first()
Iterable under test.
By default available assertions after first() are Object assertions, it is possible though to
get more specific assertions if you create IterableAssert with either:
assertThat(Iterable, element assert class)assertThat(Iterable, element assert factory)
Example: default Object assertions
// default iterable assert => element assert is ObjectAssert
Iterable<TolkienCharacter> hobbits = newArrayList(frodo, sam, pippin);
// assertion succeeds, only Object assertions are available after first()
assertThat(hobbits).first()
.isEqualTo(frodo);
// assertion fails
assertThat(hobbits).first()
.isEqualTo(pippin);
If you have created the Iterable assertion using an AssertFactory or the element assert class,
you will be able to chain first() with more specific typed assertion.
Example: use of String assertions after first()
Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");
// assertion succeeds
// String assertions are available after first()
assertThat(hobbits, StringAssert.class).first()
.startsWith("Fro")
.endsWith("do");
// assertion fails
assertThat(hobbits, StringAssert.class).first()
.startsWith("Pip");AssertionError - if the actual Iterable is empty.first(InstanceOfAssertFactory)public <ASSERT extends AbstractAssert<?,?>> ASSERT first(InstanceOfAssertFactory<?,ASSERT> assertFactory)
Iterable under test.
The assertFactory parameter allows to specify an InstanceOfAssertFactory, which is used to get the
assertions narrowed to the factory type.
Example: use of String assertions after first(as(InstanceOfAssertFactories.STRING)
Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");
// assertion succeeds
assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING))
.startsWith("Fro")
.endsWith("do");
// assertion fails
assertThat(hobbits).first(as(InstanceOfAssertFactories.STRING))
.startsWith("Pip");
// assertion fails because of wrong factory type
assertThat(hobbits).first(as(InstanceOfAssertFactories.INTEGER))
.isZero();ASSERT - the type of the resulting AssertassertFactory - the factory which verifies the type and creates the new AssertAssert instance for assertions chaining on the first elementAssertionError - if the actual Iterable is empty.NullPointerException - if the given factory is nullpublic ELEMENT_ASSERT last()
Iterable under test.
By default available assertions after last() are Object assertions, it is possible though to
get more specific assertions if you create IterableAssert with either:
assertThat(Iterable, element assert class)assertThat(Iterable, element assert factory)
Example: default Object assertions
// default iterable assert => element assert is ObjectAssert
Iterable<TolkienCharacter> hobbits = newArrayList(frodo, sam, pippin);
// assertion succeeds, only Object assertions are available after last()
assertThat(hobbits).last()
.isEqualTo(pippin);
// assertion fails
assertThat(hobbits).last()
.isEqualTo(frodo);
If you have created the Iterable assertion using an AssertFactory or the element assert class,
you will be able to chain last() with more specific typed assertion.
Example: use of String assertions after last()
Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");
// assertion succeeds
// String assertions are available after last()
assertThat(hobbits, StringAssert.class).last()
.startsWith("Pi")
.endsWith("in");
// assertion fails
assertThat(hobbits, StringAssert.class).last()
.startsWith("Fro");AssertionError - if the actual Iterable is empty.last(InstanceOfAssertFactory)public <ASSERT extends AbstractAssert<?,?>> ASSERT last(InstanceOfAssertFactory<?,ASSERT> assertFactory)
Iterable under test.
The assertFactory parameter allows to specify an InstanceOfAssertFactory, which is used to get the
assertions narrowed to the factory type.
Example: use of String assertions after last(as(InstanceOfAssertFactories.STRING)
Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");
// assertion succeeds
assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING))
.startsWith("Pip")
.endsWith("pin");
// assertion fails
assertThat(hobbits).last(as(InstanceOfAssertFactories.STRING))
.startsWith("Fro");
// assertion fails because of wrong factory type
assertThat(hobbits).last(as(InstanceOfAssertFactories.INTEGER))
.isZero();ASSERT - the type of the resulting AssertassertFactory - the factory which verifies the type and creates the new AssertAssert instance for assertions chaining on the last elementAssertionError - if the actual Iterable is empty.NullPointerException - if the given factory is nullpublic ELEMENT_ASSERT element(int index)
Iterable under test.
By default available assertions after element(index) are Object assertions, it is possible though to
get more specific assertions if you create IterableAssert with either:
assertThat(Iterable, element assert class)assertThat(Iterable, element assert factory)
Example: default Object assertions
// default iterable assert => element assert is ObjectAssert
Iterable<TolkienCharacter> hobbits = newArrayList(frodo, sam, pippin);
// assertion succeeds, only Object assertions are available after element(index)
assertThat(hobbits).element(1)
.isEqualTo(sam);
// assertion fails
assertThat(hobbits).element(1)
.isEqualTo(pippin);
If you have created the Iterable assertion using an AssertFactory or the element assert class,
you will be able to chain element(index) with more specific typed assertion.
Example: use of String assertions after element(index)
Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");
// assertion succeeds
// String assertions are available after element(index)
assertThat(hobbits, StringAssert.class).element(1)
.startsWith("Sa")
.endsWith("am");
// assertion fails
assertThat(hobbits, StringAssert.class).element(1)
.startsWith("Fro");index - the element's indexAssertionError - if the given index is out of bound.element(int, InstanceOfAssertFactory)public SELF elements(int... indices)
Iterable under test is changed to an iterable with the selected elements).
Example:
Iterable<TolkienCharacter> hobbits = newArrayList(frodo, sam, pippin);
// assertion succeeds
assertThat(hobbits).elements(1, 2)
.hasSize(2)
.containsExactly(sam, pippin);
// assertion fails
assertThat(hobbits).element(1, 2)
.containsExactly(frodo, pippin);
indices - the elements indicesIllegalArgumentException - if indices array is null or emptyAssertionError - if one of the given indices is out of bound or if the actual is emptyprotected SELF newAbstractIterableAssertForProxy(List<ELEMENT> filteredIterable)
public <ASSERT extends AbstractAssert<?,?>> ASSERT element(int index, InstanceOfAssertFactory<?,ASSERT> assertFactory)
Iterable under test.
The assertFactory parameter allows to specify an InstanceOfAssertFactory, which is used to get the
assertions narrowed to the factory type.
Example: use of String assertions after element(index, as(InstanceOfAssertFactories.STRING)
Iterable<String> hobbits = newArrayList("Frodo", "Sam", "Pippin");
// assertion succeeds
assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING))
.startsWith("Sa")
.endsWith("am");
// assertion fails
assertThat(hobbits).element(1, as(InstanceOfAssertFactories.STRING))
.startsWith("Fro");
// assertion fails because of wrong factory type
assertThat(hobbits).element(1, as(InstanceOfAssertFactories.INTEGER))
.isZero();ASSERT - the type of the resulting Assertindex - the element's indexassertFactory - the factory which verifies the type and creates the new AssertAssert instance for assertions chaining on the element at the given indexAssertionError - if the given index is out of bound.NullPointerException - if the given factory is nullpublic ELEMENT_ASSERT singleElement()
Iterable under test contains a single element and allows to perform assertions on that element.
This is a shorthand for hasSize(1).first().
By default available assertions after singleElement() are Object assertions, it is possible though to
get more specific assertions if you create IterableAssert with either:
assertThat(Iterable, element assert class)assertThat(Iterable, element assert factory)assertThat(Iterable) and narrow down the single element with an assert factory, see: singleElement(element assert factory)Example:
List<String> babySimpsons = list("Maggie");
// assertion succeeds, only Object assertions are available after singleElement()
assertThat(babySimpsons).singleElement()
.isEqualTo("Maggie");
// assertion fails
assertThat(babySimpsons).singleElement()
.isEqualTo("Homer");
// assertion fails because list contains no elements
assertThat(emptyList()).singleElement();
// assertion fails because list contains more than one element
List<String> simpsons = list("Homer", "Marge", "Lisa", "Bart", "Maggie");
assertThat(simpsons).singleElement();
If you have created the Iterable assertion using an AssertFactory or the element assert class,
you will be able to chain singleElement() with more specific typed assertion.
Example: use of String assertions after singleElement()
List<String> babySimpsons = list("Maggie");
// assertion succeeds
// String assertions are available after singleElement()
assertThat(babySimpsons, StringAssert.class).singleElement()
.startsWith("Mag");
// InstanceOfAssertFactories.STRING is an AssertFactory for String assertions
assertThat(babySimpsons, InstanceOfAssertFactories.STRING).singleElement()
.startsWith("Mag");
// better readability with import static InstanceOfAssertFactories.STRING and Assertions.as
assertThat(babySimpsons, as(STRING)).singleElement()
.startsWith("Mag");
// assertions fail
assertThat(babySimpsons, StringAssert.class).singleElement()
.startsWith("Lis");
// failure as the single element is not an int/Integer
assertThat(babySimpsons, IntegerAssert.class).singleElement()
.startsWith("Lis");AssertionError - if the actual Iterable does not contain exactly one element.singleElement(InstanceOfAssertFactory)public <ASSERT extends AbstractAssert<?,?>> ASSERT singleElement(InstanceOfAssertFactory<?,ASSERT> assertFactory)
Iterable under test contains a single element and allows to perform assertions on that element,
the assertions are strongly typed according to the given AssertFactory parameter.
This is a shorthand for hasSize(1).first(assertFactory).
Example: use of String assertions after singleElement(as(STRING))
import static org.assertj.core.api.InstanceOfAssertFactories.STRING;
import static org.assertj.core.api.InstanceOfAssertFactories.INTEGER;
import static org.assertj.core.api.Assertions.as; // syntactic sugar
List<String> babySimpsons = list("Maggie");
// assertion succeeds
assertThat(babySimpsons).singleElement(as(STRING))
.startsWith("Mag");
// assertion fails
assertThat(babySimpsons).singleElement(as(STRING))
.startsWith("Lis");
// assertion fails because of wrong factory type
assertThat(babySimpsons).singleElement(as(INTEGER))
.isZero();
// assertion fails because list contains no elements
assertThat(emptyList()).singleElement(as(STRING));
// assertion fails because list contains more than one element
List<String> simpsons = list("Homer", "Marge", "Lisa", "Bart", "Maggie");
assertThat(simpsons).singleElement(as(STRING));ASSERT - the type of the resulting AssertassertFactory - the factory which verifies the type and creates the new AssertAssert instance for assertions chaining on the single elementAssertionError - if the actual Iterable does not contain exactly one element.NullPointerException - if the given factory is null.protected abstract ELEMENT_ASSERT toAssert(ELEMENT value, String description)
first(), last() and element(int) to build the
assertion for the given element navigated to.
Typical implementation is returning an ObjectAssert but it is possible to return a more specialized assertions
should you know what type of elements the iterables contain.
value - the element valuedescription - describes the element, ex: "check first element" for first(), used in assertion description.public SELF filteredOn(Predicate<? super ELEMENT> predicate)
Predicate.
Example: check old employees whose age > 100:
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
List<Employee> employees = newArrayList(yoda, luke, obiwan);
assertThat(employees).filteredOn(employee -> employee.getAge() > 100)
.containsOnly(yoda, obiwan);predicate - the filter predicateIllegalArgumentException - if the given predicate is null.public SELF allMatch(Predicate<? super ELEMENT> predicate)
Predicate.
Example :
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
// assertion will pass
assertThat(abc).allMatch(s -> s.length() == 1);
// assertion will fail
assertThat(abcc).allMatch(s -> s.length() == 1);
Note that you can achieve the same result with are(Condition) or have(Condition).allMatch in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>predicate - the given Predicate.this object.public SELF allMatch(Predicate<? super ELEMENT> predicate, String predicateDescription)
Predicate. The predicate description is used
to get an informative error message.
Example :
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
// assertion will pass
assertThat(abc).allMatch(s -> s.length() == 1, "length of 1");
// assertion will fail
assertThat(abcc).allMatch(s -> s.length() == 1, "length of 1");
The message of the failed assertion would be:
Expecting all elements of:
<["a", "b", "cc"]>
to match 'length of 1' predicate but this element did not:
<"cc">allMatch in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>predicate - the given Predicate.predicateDescription - a description of the Predicate used in the error messagethis object.public SELF allSatisfy(Consumer<? super ELEMENT> requirements)
Consumer.
This is useful to perform a group of assertions on elements.
Example:
assertThat(myIcelanderFriends).allSatisfy(person -> {
assertThat(person.getCountry()).isEqualTo("Iceland");
assertThat(person.getPhoneCountryCode()).isEqualTo("+354");
});
If the actual iterable is empty, this assertion succeeds as there is no elements to check.
allSatisfy in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>requirements - the given Consumer.this object.public SELF allSatisfy(ThrowingConsumer<? super ELEMENT> requirements)
ThrowingConsumer.
This is useful to perform a group of assertions on elements.
This is the same assertion as ObjectEnumerableAssert.allSatisfy(Consumer) but the given consumer can throw checked exceptions.
More precisely, RuntimeException and AssertionError are rethrown as they are and Throwable wrapped in a RuntimeException.
Example:
// read() throws IOException
// note that the code would not compile if isNotEmpty, startsWithA or startsWithZ were declared as a Consumer<Reader>
ThrowingConsumer<Reader> isNotEmpty = reader -> assertThat(reader.read()).isEqualTo(-1);
ThrowingConsumer<Reader> startsWithA = reader -> assertThat(reader.read()).isEqualTo('A');
// ABC.txt contains: ABC
// XYZ.txt contains: XYZ
Iterable<FileReader> fileReaders = Arrays.asList(new FileReader("ABC.txt"), new FileReader("XYZ.txt"));
// assertion succeeds as none of the files are empty
assertThat(fileReaders).allSatisfy(isNotEmpty);
// assertion fails as XYZ.txt does not start with 'A':
assertThat(fileReaders).allSatisfy(startsWithA);
If the actual iterable is empty, this assertion succeeds as there is nothing to check.
allSatisfy in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>requirements - the given ThrowingConsumer.this object.public SELF anyMatch(Predicate<? super ELEMENT> predicate)
Predicate.
Example :
Iterable<String> abcc = newArrayList("a", "b", "cc");
// assertion will pass
assertThat(abcc).anyMatch(s -> s.length() == 2);
// assertion will fail
assertThat(abcc).anyMatch(s -> s.length() > 2);
Note that you can achieve the same result with areAtLeastOne(Condition)
or haveAtLeastOne(Condition).anyMatch in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>predicate - the given Predicate.this object.public <OTHER_ELEMENT> SELF zipSatisfy(Iterable<OTHER_ELEMENT> other, BiConsumer<? super ELEMENT,OTHER_ELEMENT> zipRequirements)
zipRequirements.
This assertion assumes that actual and other have the same size but they can contain different type of elements making it handy to compare objects converted to another type, for example Domain and View/DTO objects.
Example:
List<Adress> addressModels = findGoodRestaurants();
List<AdressView> addressViews = convertToView(addressModels);
// compare addressViews and addressModels respective paired elements.
assertThat(addressViews).zipSatisfy(addressModels, (AdressView view, Adress model) -> {
assertThat(view.getZipcode() + ' ' + view.getCity()).isEqualTo(model.getCityLine());
assertThat(view.getStreet()).isEqualTo(model.getStreet().toUpperCase());
});OTHER_ELEMENT - the type of the other iterable elements.other - the iterable to zip actual with.zipRequirements - the given requirements that each pair must satisfy.this assertion object.NullPointerException - if the given zipRequirements BiConsumer is null.NullPointerException - if the other iterable to zip actual with is null.AssertionError - if the Iterable under test is null.AssertionError - if actual and other don't have the same size.AssertionError - if one or more pairs don't satisfy the given requirements.public SELF anySatisfy(Consumer<? super ELEMENT> requirements)
Consumer.
This is useful to check that a group of assertions is verified by (at least) one element.
If the group of elements to assert is empty, the assertion will fail.
Example:
// assume that one icelander in myIcelanderFriends has a name finishing by 'son'
assertThat(myIcelanderFriends).anySatisfy(person -> {
assertThat(person.getCountry()).isEqualTo("Iceland");
assertThat(person.getSurname()).endsWith("son");
});
// assertion fails for empty group, whatever the requirements are.
assertThat(emptyGroup).anySatisfy($ -> assertThat(true).isTrue());anySatisfy in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>requirements - the given Consumer.this object.public SELF anySatisfy(ThrowingConsumer<? super ELEMENT> requirements)
ThrowingConsumer.
This is useful to check that a group of assertions is verified by (at least) one element.
This is the same assertion as ObjectEnumerableAssert.anySatisfy(Consumer) but the given consumer can throw checked exceptions.
More precisely, RuntimeException and AssertionError are rethrown as they are and Throwable wrapped in a RuntimeException.
Example:
// read() throws IOException
// note that the code would not compile if startsWithA, startsWithY or startsWithZ were declared as a Consumer<Reader>
ThrowingConsumer<Reader> startsWithA = reader -> assertThat(reader.read()).isEqualTo('A');
ThrowingConsumer<Reader> startsWithZ = reader -> assertThat(reader.read()).isEqualTo('Z');
// ABC.txt contains: ABC
// XYZ.txt contains: XYZ
Iterable<FileReader> fileReaders = Arrays.asList(new FileReader("ABC.txt"), new FileReader("XYZ.txt"));
// assertion succeeds as ABC.txt starts with 'A'
assertThat(fileReaders).anySatisfy(startsWithA);
// assertion fails none of the files starts with 'Z':
assertThat(fileReaders).anySatisfy(startsWithZ);
If the actual iterable is empty, this assertion succeeds as there is nothing to check.
anySatisfy in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>requirements - the given ThrowingConsumer.this object.public SELF noneSatisfy(Consumer<? super ELEMENT> restrictions)
Consumer.
Example:
// assume that all icelander in myIcelanderFriends are not from Brazil
assertThat(myIcelanderFriends).noneSatisfy(person -> {
assertThat(person.getCountry()).isEqualTo("Brazil");
});
Note that this assertion succeeds if the group (collection, array, ...) is empty whatever the restrictions are.noneSatisfy in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>restrictions - the given restrictions as Consumer that no elements should met.this object.public SELF noneSatisfy(ThrowingConsumer<? super ELEMENT> restrictions)
Consumer.
This is useful to check that a group of assertions is verified by (at least) one element.
This is the same assertion as ObjectEnumerableAssert.anySatisfy(Consumer) but the given consumer can throw checked exceptions.
More precisely, RuntimeException and AssertionError are rethrown as they are and Throwable wrapped in a RuntimeException.
Example:
// read() throws IOException
// note that the code would not compile if startsWithA, startsWithY or startsWithZ were declared as a Consumer<Reader>
ThrowingConsumer<Reader> startsWithA = reader -> assertThat(reader.read()).isEqualTo('A');
ThrowingConsumer<Reader> startsWithZ = reader -> assertThat(reader.read()).isEqualTo('Z');
// ABC.txt contains: ABC
// XYZ.txt contains: XYZ
Iterable<FileReader> fileReaders = Arrays.asList(new FileReader("ABC.txt"), new FileReader("XYZ.txt"));
// assertion succeeds as none of the file starts 'Z'
assertThat(fileReaders).noneSatisfy(startsWithZ);
// assertion fails as ABC.txt starts with 'A':
assertThat(fileReaders).noneSatisfy(startsWithA);
Note that this assertion succeeds if the group (collection, array, ...) is empty whatever the restrictions are.
noneSatisfy in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>restrictions - the given ThrowingConsumer.this object.@SafeVarargs public final SELF satisfiesExactly(Consumer<? super ELEMENT>... requirements)
Each requirements are expressed as a Consumer, there must be as many requirements as there are iterable elements.
Example:
Iterable<TolkienCharacter> characters = list(frodo, aragorn, legolas);
// assertions succeed
assertThat(characters).satisfiesExactly(character -> assertThat(character.getRace()).isEqualTo("Hobbit"),
character -> assertThat(character.isMortal()).isTrue(),
character -> assertThat(character.getName()).isEqualTo("Legolas"));
// you can specify more than one assertion per requirement
assertThat(characters).satisfiesExactly(character -> {
assertThat(character.getRace()).isEqualTo("Hobbit");
assertThat(character.getName()).isEqualTo("Frodo");
},
character -> {
assertThat(character.isMortal()).isTrue();
assertThat(character.getName()).isEqualTo("Aragorn");
},
character -> {
assertThat(character.getRace()).isEqualTo("Elf");
assertThat(character.getName()).isEqualTo("Legolas");
});
// assertion fails as aragorn does not meet the second requirements
assertThat(characters).satisfiesExactly(character -> assertThat(character.getRace()).isEqualTo("Hobbit"),
character -> assertThat(character.isMortal()).isFalse(),
character -> assertThat(character.getName()).isEqualTo("Legolas"));satisfiesExactly in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>requirements - the requirements to meet.this to chain assertions.@SafeVarargs public final SELF satisfiesExactly(ThrowingConsumer<? super ELEMENT>... requirements)
Each requirements are expressed as a ThrowingConsumer, there must be as many requirements as there are iterable elements.
This is the same assertion as ObjectEnumerableAssert.satisfiesExactly(Consumer...) but the given consumers can throw checked exceptions.
More precisely, RuntimeException and AssertionError are rethrown as they are and Throwable wrapped in a RuntimeException.
Example:
Iterable<TolkienCharacter> characters = list(frodo, aragorn, legolas);
// the code would compile even if TolkienCharacter.getRace(), isMortal() or getName() threw a checked exception
// assertions succeed
assertThat(characters).satisfiesExactly(character -> assertThat(character.getRace()).isEqualTo("Hobbit"),
character -> assertThat(character.isMortal()).isTrue(),
character -> assertThat(character.getName()).isEqualTo("Legolas"));
// you can specify more than one assertion per requirement
assertThat(characters).satisfiesExactly(character -> {
assertThat(character.getRace()).isEqualTo("Hobbit");
assertThat(character.getName()).isEqualTo("Frodo");
},
character -> {
assertThat(character.isMortal()).isTrue();
assertThat(character.getName()).isEqualTo("Aragorn");
},
character -> {
assertThat(character.getRace()).isEqualTo("Elf");
assertThat(character.getName()).isEqualTo("Legolas");
});
// assertion fails as aragorn does not meet the second requirements
assertThat(characters).satisfiesExactly(character -> assertThat(character.getRace()).isEqualTo("Hobbit"),
character -> assertThat(character.isMortal()).isFalse(),
character -> assertThat(character.getName()).isEqualTo("Legolas"));satisfiesExactly in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>requirements - the requirements to meet.this to chain assertions.protected SELF satisfiesExactlyForProxy(Consumer<? super ELEMENT>[] requirements)
@SafeVarargs public final SELF satisfiesExactlyInAnyOrder(Consumer<? super ELEMENT>... requirements)
This is a variation of ObjectEnumerableAssert.satisfiesExactly(Consumer...) where order does not matter.
Examples:
List<String> starWarsCharacterNames = list("Luke", "Leia", "Yoda");
// these assertions succeed:
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Y"), // matches "Yoda"
name -> assertThat(name).contains("L"), // matches "Luke" and "Leia"
name -> {
assertThat(name).hasSize(4);
assertThat(name).doesNotContain("a"); // matches "Luke" but not "Leia"
})
.satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Yo"),
name -> assertThat(name).contains("Lu"),
name -> assertThat(name).contains("Le"))
.satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Le"),
name -> assertThat(name).contains("Yo"),
name -> assertThat(name).contains("Lu"));
// this assertion fails as 3 consumer/requirements are expected
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Y"),
name -> assertThat(name).contains("L"));
// this assertion fails as no element contains "Han" (first consumer/requirements can't be met)
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Han"),
name -> assertThat(name).contains("L"),
name -> assertThat(name).contains("Y"));
// this assertion fails as "Yoda" element can't satisfy any consumers/requirements (even though all consumers/requirements are met)
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("L"),
name -> assertThat(name).contains("L"),
name -> assertThat(name).contains("L"));
// this assertion fails as no combination of elements can satisfy the consumers in order
// the problem is if the last consumer is matched by Leia then no other consumer can match Luke (and vice versa)
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Y"),
name -> assertThat(name).contains("o"),
name -> assertThat(name).contains("L"));satisfiesExactlyInAnyOrder in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>requirements - the consumers that are expected to be satisfied by the elements of the given Iterable.@SafeVarargs public final SELF satisfiesExactlyInAnyOrder(ThrowingConsumer<? super ELEMENT>... requirements)
ThrowingConsumers in order (there must be as
many consumers as iterable elements and once a consumer is matched it cannot be reused to match other elements).
This is a variation of ObjectEnumerableAssert.satisfiesExactly(ThrowingConsumer...) where order does not matter.
Examples:
List<String> starWarsCharacterNames = list("Luke", "Leia", "Yoda");
// these assertions succeed:
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Y"), // matches "Yoda"
name -> assertThat(name).contains("L"), // matches "Luke" and "Leia"
name -> {
assertThat(name).hasSize(4);
assertThat(name).doesNotContain("a"); // matches "Luke" but not "Leia"
})
.satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Yo"),
name -> assertThat(name).contains("Lu"),
name -> assertThat(name).contains("Le"))
.satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Le"),
name -> assertThat(name).contains("Yo"),
name -> assertThat(name).contains("Lu"));
// this assertion fails as 3 consumers/requirements are expected
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Y"),
name -> assertThat(name).contains("L"));
// this assertion fails as no element contains "Han" (first consumer/requirements can't be met)
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Han"),
name -> assertThat(name).contains("L"),
name -> assertThat(name).contains("Y"));
// this assertion fails as "Yoda" element can't satisfy any consumers/requirements (even though all consumers/requirements are met)
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("L"),
name -> assertThat(name).contains("L"),
name -> assertThat(name).contains("L"));
// this assertion fails as no combination of elements can satisfy the consumers in order
// the problem is if the last consumer is matched by Leia then no other consumer can match Luke (and vice versa)
assertThat(starWarsCharacterNames).satisfiesExactlyInAnyOrder(name -> assertThat(name).contains("Y"),
name -> assertThat(name).contains("o"),
name -> assertThat(name).contains("L"));satisfiesExactlyInAnyOrder in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>requirements - the consumers that are expected to be satisfied by the elements of the given Iterable.protected SELF satisfiesExactlyInAnyOrderForProxy(Consumer<? super ELEMENT>[] requirements)
public SELF as(String description, Object... args)
DescriptableYou must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
The description follows String.format(String, Object...) syntax.
Example :
try {
// set an incorrect age to Mr Frodo which is really 33 years old.
frodo.setAge(50);
// specify a test description (call as() before the assertion !), it supports String format syntax.
assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33);
} catch (AssertionError e) {
assertThat(e).hasMessage("[check Frodo's age]\n
expected: 33\n
but was: 50");
}as in interface Descriptable<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>>description - the new description to set.args - optional parameter if description is a format String.this object.Descriptable.describedAs(String, Object...)public SELF as(Description description)
DescriptableYou must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
This overloaded version of "describedAs" offers more flexibility than the one taking a String by allowing
users to pass their own implementation of a description. For example, a description that creates its value lazily,
only when an assertion failure occurs.
as in interface Descriptable<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>>description - the new description to set.this object.Descriptable.describedAs(Description)public SELF describedAs(Description description)
AbstractAssertYou must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
This overloaded version of "describedAs" offers more flexibility than the one taking a String by allowing
users to pass their own implementation of a description. For example, a description that creates its value lazily,
only when an assertion failure occurs.
describedAs in interface Descriptable<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>>describedAs in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>description - the new description to set.this object.public SELF describedAs(String description, Object... args)
DescriptableYou must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
Alias for since "as" is a keyword in Groovy.Descriptable.as(String, Object...)
describedAs in interface Descriptable<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>>description - the new description to set.args - optional parameter if description is a format String.this object.public SELF doesNotHave(Condition<? super ACTUAL> condition)
AbstractAssertExtensionPoints.isNot(Condition).doesNotHave in interface ExtensionPoints<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>doesNotHave in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>condition - the given condition.this ExtensionPoints object.ExtensionPoints.isNot(Condition)public SELF doesNotHaveSameClassAs(Object other)
AbstractAssertExample:
// assertions succeed
assertThat(1).doesNotHaveSameClassAs("abc");
assertThat(new ArrayList<String>()).doesNotHaveSameClassAs(new LinkedList<String>());
// assertions fail
assertThat(1).doesNotHaveSameClassAs(2);
assertThat("abc").doesNotHaveSameClassAs("123");
assertThat(new ArrayList<String>()).doesNotHaveSameClassAs(new ArrayList<Integer>());doesNotHaveSameClassAs in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>doesNotHaveSameClassAs in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>other - the object to check type against.public SELF has(Condition<? super ACTUAL> condition)
AbstractAssertExtensionPoints.is(Condition)
.has in interface ExtensionPoints<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>has in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>condition - the given condition.this ExtensionPoints object.ExtensionPoints.is(Condition)public SELF hasSameClassAs(Object other)
AbstractAssertExample:
// assertions succeed
assertThat(1).hasSameClassAs(2);
assertThat("abc").hasSameClassAs("123");
assertThat(new ArrayList<String>()).hasSameClassAs(new ArrayList<Integer>());
// assertions fail
assertThat(1).hasSameClassAs("abc");
assertThat(new ArrayList<String>()).hasSameClassAs(new LinkedList<String>());hasSameClassAs in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>hasSameClassAs in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>other - the object to check type against.public SELF hasToString(String expectedToString)
AbstractAssertactual.toString() is equal to the given String.
Example :
CartoonCharacter homer = new CartoonCharacter("Homer");
// Instead of writing ...
assertThat(homer.toString()).isEqualTo("Homer");
// ... you can simply write:
assertThat(homer).hasToString("Homer");hasToString in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>hasToString in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>expectedToString - the expected String description of actual.public SELF is(Condition<? super ACTUAL> condition)
AbstractAssertExtensionPoints.has(Condition).is in interface ExtensionPoints<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>is in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>condition - the given condition.this ExtensionPoints object.ExtensionPoints.has(Condition)public SELF isEqualTo(Object expected)
AbstractAssertExample:
// assertions succeed
assertThat("abc").isEqualTo("abc");
assertThat(new HashMap<String, Integer>()).isEqualTo(new HashMap<String, Integer>());
// assertions fail
assertThat("abc").isEqualTo("123");
assertThat(new ArrayList<String>()).isEqualTo(1);isEqualTo in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isEqualTo in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>expected - the given value to compare the actual value to.this assertion object.public SELF isExactlyInstanceOf(Class<?> type)
AbstractAssertExample:
// assertions succeed
assertThat("abc").isExactlyInstanceOf(String.class);
assertThat(new ArrayList<String>()).isExactlyInstanceOf(ArrayList.class);
assertThat(new HashMap<String, Integer>()).isExactlyInstanceOf(HashMap.class);
// assertions fail
assertThat(1).isExactlyInstanceOf(String.class);
assertThat(new ArrayList<String>()).isExactlyInstanceOf(List.class);
assertThat(new HashMap<String, Integer>()).isExactlyInstanceOf(Map.class);isExactlyInstanceOf in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isExactlyInstanceOf in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>type - the type to check the actual value against.public SELF isIn(Iterable<?> values)
AbstractAssertThis assertion always fails if the given iterable is empty.
Example:
Iterable<Ring> elvesRings = list(vilya, nenya, narya);
// assertion succeeds
assertThat(nenya).isIn(elvesRings);
// assertions fail:
assertThat(oneRing).isIn(elvesRings);
assertThat(oneRing).isIn(emptyList());isIn in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isIn in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>values - the given iterable to search the actual value in.this assertion object.public SELF isIn(Object... values)
AbstractAssertThis assertion always fails if the given array of values is empty.
Example:
Ring[] elvesRings = new Ring[] { vilya, nenya, narya };
// assertion succeeds
assertThat(nenya).isIn(elvesRings);
// assertions fail
assertThat(oneRing).isIn(elvesRings);
assertThat(oneRing).isIn(new Ring[0]);isIn in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isIn in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>values - the given array to search the actual value in.this assertion object.public SELF isInstanceOf(Class<?> type)
AbstractAssertExample:
// assertions succeed
assertThat("abc").isInstanceOf(String.class);
assertThat(new HashMap<String, Integer>()).isInstanceOf(HashMap.class);
assertThat(new HashMap<String, Integer>()).isInstanceOf(Map.class);
// assertions fail
assertThat(1).isInstanceOf(String.class);
assertThat(new ArrayList<String>()).isInstanceOf(LinkedList.class);isInstanceOf in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isInstanceOf in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>type - the type to check the actual value against.public SELF isInstanceOfAny(Class<?>... types)
AbstractAssertExample:
// assertions succeed
assertThat("abc").isInstanceOfAny(String.class, Integer.class);
assertThat(new ArrayList<String>()).isInstanceOfAny(LinkedList.class, ArrayList.class);
assertThat(new HashMap<String, Integer>()).isInstanceOfAny(TreeMap.class, Map.class);
// assertions fail
assertThat(1).isInstanceOfAny(Double.class, Float.class);
assertThat(new ArrayList<String>()).isInstanceOfAny(LinkedList.class, Vector.class);isInstanceOfAny in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isInstanceOfAny in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>types - the types to check the actual value against.public SELF isNot(Condition<? super ACTUAL> condition)
AbstractAssertExtensionPoints.doesNotHave(Condition).isNot in interface ExtensionPoints<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNot in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>condition - the given condition.this ExtensionPoints object.ExtensionPoints.isNot(Condition)public SELF isNotEqualTo(Object other)
AbstractAssertExample:
// assertions succeed
assertThat("abc").isNotEqualTo("123");
assertThat(new ArrayList<String>()).isNotEqualTo(1);
// assertions fail
assertThat("abc").isNotEqualTo("abc");
assertThat(new HashMap<String, Integer>()).isNotEqualTo(new HashMap<String, Integer>());isNotEqualTo in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotEqualTo in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>other - the given value to compare the actual value to.this assertion object.public SELF isNotExactlyInstanceOf(Class<?> type)
AbstractAssertExample:
// assertions succeed
assertThat(1).isNotExactlyInstanceOf(String.class);
assertThat(new ArrayList<String>()).isNotExactlyInstanceOf(List.class);
assertThat(new HashMap<String, Integer>()).isNotExactlyInstanceOf(Map.class);
// assertions fail
assertThat("abc").isNotExactlyInstanceOf(String.class);
assertThat(new ArrayList<String>()).isNotExactlyInstanceOf(ArrayList.class);
assertThat(new HashMap<String, Integer>()).isNotExactlyInstanceOf(HashMap.class);isNotExactlyInstanceOf in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotExactlyInstanceOf in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>type - the type to check the actual value against.public SELF isNotIn(Iterable<?> values)
AbstractAssertThis assertion always succeeds if the given iterable is empty.
Example:
Iterable<Ring> elvesRings = list(vilya, nenya, narya);
// assertions succeed:
assertThat(oneRing).isNotIn(elvesRings);
assertThat(oneRing).isNotIn(emptyList());
// assertions fails:
assertThat(nenya).isNotIn(elvesRings);isNotIn in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotIn in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>values - the given iterable to search the actual value in.this assertion object.public SELF isNotIn(Object... values)
AbstractAssertThis assertion always succeeds if the given array of values is empty.
Example:
Ring[] elvesRings = new Ring[] { vilya, nenya, narya };
// assertions succeed
assertThat(oneRing).isNotIn(elvesRings);
assertThat(oneRing).isNotIn(new Ring[0]);
// assertions fails:
assertThat(nenya).isNotIn(elvesRings);isNotIn in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotIn in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>values - the given array to search the actual value in.this assertion object.public SELF isNotInstanceOf(Class<?> type)
AbstractAssertExample:
// assertions succeed
assertThat(1).isNotInstanceOf(Double.class);
assertThat(new ArrayList<String>()).isNotInstanceOf(LinkedList.class);
// assertions fail
assertThat("abc").isNotInstanceOf(String.class);
assertThat(new HashMap<String, Integer>()).isNotInstanceOf(HashMap.class);
assertThat(new HashMap<String, Integer>()).isNotInstanceOf(Map.class);isNotInstanceOf in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotInstanceOf in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>type - the type to check the actual value against.public SELF isNotInstanceOfAny(Class<?>... types)
AbstractAssertExample:
// assertions succeed
assertThat(1).isNotInstanceOfAny(Double.class, Float.class);
assertThat(new ArrayList<String>()).isNotInstanceOfAny(LinkedList.class, Vector.class);
// assertions fail
assertThat(1).isNotInstanceOfAny(Double.class, Integer.class);
assertThat(new ArrayList<String>()).isNotInstanceOfAny(LinkedList.class, ArrayList.class);
assertThat(new HashMap<String, Integer>()).isNotInstanceOfAny(TreeMap.class, Map.class);isNotInstanceOfAny in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotInstanceOfAny in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>types - the types to check the actual value against.public SELF isNotOfAnyClassIn(Class<?>... types)
AbstractAssertExample:
// assertions succeed
assertThat(new HashMap<String, Integer>()).isNotOfAnyClassIn(Map.class, TreeMap.class);
assertThat(new ArrayList<String>()).isNotOfAnyClassIn(LinkedList.class, List.class);
// assertions fail
assertThat(new HashMap<String, Integer>()).isNotOfAnyClassIn(HashMap.class, TreeMap.class);
assertThat(new ArrayList<String>()).isNotOfAnyClassIn(ArrayList.class, LinkedList.class);isNotOfAnyClassIn in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotOfAnyClassIn in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>types - the types to check the actual value against.public SELF isNotNull()
AbstractAssertnull.
Example:
// assertions succeed
assertThat("abc").isNotNull();
assertThat(new HashMap<String, Integer>()).isNotNull();
// assertions fails
String value = null;
assertThat(value).isNotNull();isNotNull in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotNull in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>this assertion object.public SELF isNotSameAs(Object other)
AbstractAssertExample:
// Name is a class with first and last fields, two Names are equals if both first and last are equals.
Name tyrion = new Name("Tyrion", "Lannister");
Name alias = tyrion;
Name clone = new Name("Tyrion", "Lannister");
// assertions succeed:
assertThat(clone).isNotSameAs(tyrion)
.isEqualTo(tyrion);
// assertion fails:
assertThat(alias).isNotSameAs(tyrion);isNotSameAs in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isNotSameAs in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>other - the given value to compare the actual value to.this assertion object.public SELF isOfAnyClassIn(Class<?>... types)
AbstractAssertExample:
// assertions succeed
assertThat(new HashMap<String, Integer>()).isOfAnyClassIn(HashMap.class, TreeMap.class);
assertThat(new ArrayList<String>()).isOfAnyClassIn(ArrayList.class, LinkedList.class);
// assertions fail
assertThat(new HashMap<String, Integer>()).isOfAnyClassIn(TreeMap.class, Map.class);
assertThat(new ArrayList<String>()).isOfAnyClassIn(LinkedList.class, List.class);isOfAnyClassIn in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isOfAnyClassIn in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>types - the types to check the actual value against.public SELF isSameAs(Object expected)
AbstractAssertExample:
// Name is a class with first and last fields, two Names are equals if both first and last are equals.
Name tyrion = new Name("Tyrion", "Lannister");
Name alias = tyrion;
Name clone = new Name("Tyrion", "Lannister");
// assertions succeed:
assertThat(tyrion).isSameAs(alias)
.isEqualTo(clone);
// assertion fails:
assertThat(tyrion).isSameAs(clone);isSameAs in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>isSameAs in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>expected - the given value to compare the actual value to.this assertion object.public SELF noneMatch(Predicate<? super ELEMENT> predicate)
ObjectEnumerableAssertPredicate.
Example :
Iterable<String> abcc = newArrayList("a", "b", "cc");
// assertion will pass
assertThat(abcc).noneMatch(s -> s.isEmpty());
// assertion will fail
assertThat(abcc).noneMatch(s -> s.length() == 2);
Note that you can achieve the same result with areNot(Condition)
or doNotHave(Condition).noneMatch in interface ObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ELEMENT>predicate - the given Predicate.this object.public SELF overridingErrorMessage(String newErrorMessage, Object... args)
AbstractAssertYou must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
The new error message is built using String.format(String, Object...) if you provide args parameter (if you
don't, the error message is taken as it is).
Example :
assertThat(player.isRookie()).overridingErrorMessage("Expecting Player <%s> to be a rookie but was not.", player)
.isTrue();overridingErrorMessage in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>newErrorMessage - the error message that will replace the default one provided by Assertj.args - the args used to fill error message as in String.format(String, Object...).public SELF usingDefaultComparator()
AbstractAssert
This method should be used to disable a custom comparison strategy set by calling usingComparator.
usingDefaultComparator in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>usingDefaultComparator in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>this assertion object.public SELF usingComparator(Comparator<? super ACTUAL> customComparator)
AbstractAssertThe custom comparator is bound to assertion instance, meaning that if a new assertion instance is created, the default comparison strategy will be used.
Examples :
// frodo and sam are instances of Character with Hobbit race (obviously :).
// raceComparator implements Comparator<Character>
assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam);usingComparator in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>usingComparator in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>customComparator - the comparator to use for the incoming assertion checks.this assertion object.public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription)
AbstractAssertThe custom comparator is bound to assertion instance, meaning that if a new assertion instance is created, the default comparison strategy will be used.
Examples :
// frodo and sam are instances of Character with Hobbit race (obviously :).
// raceComparator implements Comparator<Character>
assertThat(frodo).usingComparator(raceComparator, "Hobbit Race Comparator").isEqualTo(sam);usingComparator in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>usingComparator in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>customComparator - the comparator to use for the incoming assertion checks.customComparatorDescription - comparator description to be used in assertion error messagesthis assertion object.public SELF withFailMessage(String newErrorMessage, Object... args)
AbstractAssertAbstractAssert.overridingErrorMessage(java.lang.String, java.lang.Object...)
You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
Example:
assertThat(player.isRookie()).withFailMessage("Expecting Player <%s> to be a rookie but was not.", player)
.isTrue();withFailMessage in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>newErrorMessage - the error message that will replace the default one provided by Assertj.args - the args used to fill error message as in String.format(String, Object...).public SELF withThreadDumpOnError()
AbstractAssertSystem.err.
Example :
assertThat("Messi").withThreadDumpOnError().isEqualTo("Ronaldo");
will print a thread dump, something similar to this:
"JDWP Command Reader"
java.lang.Thread.State: RUNNABLE
"JDWP Event Helper Thread"
java.lang.Thread.State: RUNNABLE
"JDWP Transport Listener: dt_socket"
java.lang.Thread.State: RUNNABLE
"Signal Dispatcher"
java.lang.Thread.State: RUNNABLE
"Finalizer"
java.lang.Thread.State: WAITING
at java.lang.Object.wait(Native Method)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:189)
"Reference Handler"
java.lang.Thread.State: WAITING
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)
"main"
java.lang.Thread.State: RUNNABLE
at sun.management.ThreadImpl.dumpThreads0(Native Method)
at sun.management.ThreadImpl.dumpAllThreads(ThreadImpl.java:446)
at org.assertj.core.internal.Failures.threadDumpDescription(Failures.java:193)
at org.assertj.core.internal.Failures.printThreadDumpIfNeeded(Failures.java:141)
at org.assertj.core.internal.Failures.failure(Failures.java:91)
at org.assertj.core.internal.Objects.assertEqual(Objects.java:314)
at org.assertj.core.api.AbstractAssert.isEqualTo(AbstractAssert.java:198)
at org.assertj.examples.ThreadDumpOnErrorExample.main(ThreadDumpOnErrorExample.java:28)withThreadDumpOnError in interface Assert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>withThreadDumpOnError in class AbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>public AbstractIterableSizeAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT> size()
Assert object that allows performing assertions on the size of the Iterable under test.
Once this method is called, the object under test is no longer the Iterable but its size,
to perform assertions on the Iterable, call AbstractIterableSizeAssert.returnToIterable().
Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass:
assertThat(elvesRings).size().isGreaterThan(1)
.isLessThanOrEqualTo(3)
.returnToIterable().contains(narya)
.doesNotContain(oneRing);
// assertion will fail:
assertThat(elvesRings).size().isGreaterThan(3);Iterable's size.NullPointerException - if the given Iterable is null.protected TypeComparators getComparatorsByType()
protected TypeComparators getComparatorsForElementPropertyOrFieldTypes()
protected abstract SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable)
If you create your own subclass of AbstractIterableAssert, simply returns an instance of it in this method.
iterable - the iterable used to build the concrete instance of AbstractIterableAssertCopyright © 2025. All rights reserved.