ELEMENT - the type of elements of the "actual" value.public abstract class AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT> extends AbstractAssert<SELF,ELEMENT[]> implements IndexedObjectEnumerableAssert<AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>, ArraySortedAssert<AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>
To create an instance of this class, invoke .
Assertions.assertThat(Object[])
actual, info, myself, objects, throwUnsupportedExceptionOnEquals| Modifier | Constructor and Description |
|---|---|
protected |
AbstractObjectArrayAssert(ELEMENT[] actual,
Class<?> selfType) |
| Modifier and Type | Method and Description |
|---|---|
SELF |
allMatch(Predicate<? super ELEMENT> predicate)
Verifies that all elements 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 array satisfying the given condition.
|
SELF |
areAtLeastOne(Condition<? super ELEMENT> condition)
Verifies that there is at least one element in the actual array satisfying the given condition.
|
SELF |
areAtMost(int times,
Condition<? super ELEMENT> condition)
Verifies that there are at most n elements in the actual array satisfying the given condition.
|
SELF |
areExactly(int times,
Condition<? super ELEMENT> condition)
Verifies that there are exactly n elements in the actual array 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 array contains the given values, in any order.
|
SELF |
contains(ELEMENT value,
Index index)
Verifies that the actual array contains the given object at the given index.
|
SELF |
containsAll(Iterable<? extends ELEMENT> iterable)
Verifies that the actual array contains all the elements of given
Iterable, in any order. |
SELF |
containsAnyElementsOf(Iterable<? extends ELEMENT> iterable)
Verifies that the actual array contains at least one of the given
Iterable elements. |
SELF |
containsAnyOf(ELEMENT... values)
Verifies that the actual array contains at least one of the given values.
|
protected SELF |
containsAnyOfForProxy(ELEMENT[] values) |
SELF |
containsExactly(ELEMENT... values)
Verifies that the actual array contains exactly the given values and nothing else, in order.
|
SELF |
containsExactlyElementsOf(Iterable<? extends ELEMENT> iterable)
Same as
containsExactly(Object...) but handles 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 array 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 array contains at least a null element.
|
SELF |
containsOnly(ELEMENT... values)
Verifies that the actual array contains only the given values and nothing else, in any order and ignoring duplicates (i.e.
|
SELF |
containsOnlyElementsOf(Iterable<? extends ELEMENT> iterable)
Same semantic as
containsOnly(Object[]) : verifies that actual contains all elements of the given
Iterable and nothing else, in any order and ignoring duplicates (i.e. |
protected SELF |
containsOnlyForProxy(ELEMENT[] values) |
SELF |
containsOnlyNulls()
Verifies that the actual array contains only null elements.
|
SELF |
containsOnlyOnce(ELEMENT... values)
Verifies that the actual array 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 array 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 array 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 array contains the given subsequence in the correct order (possibly with other values between them).
|
SELF |
containsSubsequence(Iterable<? extends ELEMENT> subsequence)
Verifies that the actual array contains the given subsequence in the correct order (possibly with other values between them).
|
protected SELF |
containsSubsequenceForProxy(ELEMENT[] subsequence) |
SELF |
doesNotContain(ELEMENT... values)
Verifies that the actual array does not contain the given values.
|
SELF |
doesNotContain(ELEMENT value,
Index index)
Verifies that the actual array does not contain the given object at the given index.
|
SELF |
doesNotContainAnyElementsOf(Iterable<? extends ELEMENT> iterable)
Verifies that the actual array does not contain any elements of the given
Iterable (i.e. |
protected SELF |
doesNotContainForProxy(ELEMENT[] values) |
SELF |
doesNotContainNull()
Verifies that the actual array does not contain null elements.
|
SELF |
doesNotContainSequence(ELEMENT... sequence)
Verifies that the actual array does not contain the given sequence in the given order and without extra values between the sequence values.
|
SELF |
doesNotContainSequence(Iterable<? extends ELEMENT> sequence)
Verifies that the actual array does not contain the given sequence in the given order and without extra values between the sequence values.
|
protected SELF |
doesNotContainSequenceForProxy(ELEMENT[] sequence) |
SELF |
doesNotContainSubsequence(ELEMENT... subsequence)
Verifies that the actual array does not contain the given subsequence in the correct order (possibly with other
values between them).
|
SELF |
doesNotContainSubsequence(Iterable<? extends ELEMENT> subsequence)
Verifies that the actual array does not contain the given subsequence in the correct order (possibly with other
values between them).
|
protected SELF |
doesNotContainSubsequenceForProxy(ELEMENT[] subsequence) |
SELF |
doesNotHaveAnyElementsOfTypes(Class<?>... unexpectedTypes)
Verifies that all the elements in the actual
Object group do not belong to the specified types (including subclasses). |
SELF |
doesNotHaveDuplicates()
Verifies that the actual array does not contain duplicates.
|
SELF |
doNotHave(Condition<? super ELEMENT> condition)
Verifies that all elements don't satisfy the given condition.
|
SELF |
endsWith(ELEMENT[] sequence)
Verifies that the actual array ends with the given sequence of objects, without any other objects between them.
|
SELF |
endsWith(ELEMENT first,
ELEMENT... sequence)
Verifies that the actual array ends with the given sequence of objects, without any other objects between them.
|
protected SELF |
endsWithForProxy(ELEMENT first,
ELEMENT[] sequence) |
AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> |
extracting(Function<? super ELEMENT,?>... extractors)
|
<U> AbstractListAssert<?,List<? extends U>,U,ObjectAssert<U>> |
extracting(Function<? super ELEMENT,U> extractor)
Extract the values from the array's elements by applying an extracting function on them, the resulting list becomes
the new object under test.
|
AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> |
extracting(String... propertiesOrFields)
Extract the values of given fields/properties from the array's elements under test into a list composed of
Tuple (a simple data structure), this new list becoming the object under test.
|
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
extracting(String fieldOrProperty)
Extract the values of given field or property from the array's elements under test into a new list, this new list
becoming the object under test.
|
<P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> |
extracting(String fieldOrProperty,
Class<P> extractingType)
Extract the values of given field or property from the array's elements under test into a new list, this new list of the provided type
becoming the object under test.
|
<V,EXCEPTION extends Exception> |
extracting(ThrowingExtractor<? super ELEMENT,V,EXCEPTION> extractor)
Extract the values from the array's elements by applying an extracting function (which might throw an exception)
on them, the resulting list of extracted values becomes a new object under test.
|
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 from the array's elements under test into a list, this list becoming
the object under test.
|
<P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> |
extractingResultOf(String method,
Class<P> extractingType)
Extract the result of given method invocation from the array's elements under test into a list, this list becoming
the object under test.
|
SELF |
filteredOn(Condition<? super ELEMENT> condition)
Filter the array under test into a list composed of the elements matching the given
Condition,
allowing to perform assertions on the filtered list. |
<T> SELF |
filteredOn(Function<? super ELEMENT,T> function,
T expectedValue)
Filter the array under test into a list composed of the elements for which the result of the
function is equal to expectedValue. |
SELF |
filteredOn(Predicate<? super ELEMENT> predicate)
Filter the array under test into a list composed of the elements matching the given
Predicate,
allowing to perform assertions on the filtered list. |
SELF |
filteredOn(String propertyOrFieldName,
FilterOperator<?> filterOperator)
Filter the array under test into a list composed of 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)
Filter the array under test into a list composed of the elements elements having a property or field equal to
expectedValue, the property/field is specified by propertyOrFieldName parameter. |
SELF |
filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions)
Filter the array under test keeping only elements matching the given assertions specified with a
Consumer. |
SELF |
filteredOnAssertions(ThrowingConsumer<? super ELEMENT> elementAssertions)
Filter the array under test keeping only elements matching the given assertions specified with a
Consumer. |
SELF |
filteredOnNull(String propertyOrFieldName)
Filter the array under test into a list composed of the elements whose property or field specified
by
propertyOrFieldName are null. |
<V,C extends Collection<V>> |
flatExtracting(Function<? super ELEMENT,C> extractor)
Extract the Iterable values from arrays elements under test by applying an Iterable extracting function on them
and concatenating the result lists into an array which becomes the new object under test.
|
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> |
flatExtracting(String propertyName)
Extract from array's elements the Iterable/Array values corresponding to the given property/field name and
concatenate them into a single array becoming the new object under test.
|
<V,C extends Collection<V>,EXCEPTION extends Exception> |
flatExtracting(ThrowingExtractor<? super ELEMENT,C,EXCEPTION> extractor)
Extract the Iterable values from arrays elements under test by applying an Iterable extracting function (which
might throw an exception) on them and concatenating the result lists into an array which becomes the new object
under test.
|
protected TypeComparators |
getComparatorsByType() |
protected TypeComparators |
getComparatorsForElementPropertyOrFieldTypes() |
SELF |
hasAtLeastOneElementOfType(Class<?> type)
Verifies that at least one element in the actual
Object group has the specified type (matching
includes subclasses of the given type). |
SELF |
hasExactlyElementsOfTypes(Class<?>... expectedTypes)
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<?> type)
Verifies that all the elements in the actual
Object group belong to the specified type (matching includes
subclasses of the given type). |
SELF |
hasOnlyElementsOfTypes(Class<?>... types)
Verifies that all elements of the actual array are instances of given classes or interfaces.
|
SELF |
hasOnlyOneElementSatisfying(Consumer<? super ELEMENT> elementAssertions)
Verifies that the unique element of the array 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. |
SELF |
hasSameElementsAs(Iterable<? extends ELEMENT> iterable)
An alias of
containsOnlyElementsOf(Iterable) : verifies that actual contains all elements of the
given Iterable and nothing else, in any order. |
SELF |
hasSameSizeAs(Iterable<?> other)
Verifies that the actual array has the same size as the given
Iterable. |
SELF |
hasSameSizeAs(Object other)
Verifies that the actual array has the same size as the 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 array is between the given boundaries (inclusive).
|
SELF |
hasSizeGreaterThan(int boundary)
Verifies that the number of values in the actual array is greater than the given boundary.
|
SELF |
hasSizeGreaterThanOrEqualTo(int boundary)
Verifies that the number of values in the actual array is greater than or equal to the given boundary.
|
SELF |
hasSizeLessThan(int boundary)
Verifies that the number of values in the actual array is less than the given boundary.
|
SELF |
hasSizeLessThanOrEqualTo(int boundary)
Verifies that the number of values in the actual array is less than or equal to the given boundary.
|
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 array satisfying the given condition.
|
SELF |
haveAtLeastOne(Condition<? super ELEMENT> condition)
Verifies that there is at least one element in the actual array satisfying the given condition.
|
SELF |
haveAtMost(int times,
Condition<? super ELEMENT> condition)
Verifies that there are at most n elements in the actual array satisfying the given condition.
|
SELF |
haveExactly(int times,
Condition<? super ELEMENT> condition)
Verifies that there are exactly n elements in the actual array satisfying the given condition.
|
SELF |
inBinary()
Use binary object representation instead of standard representation in error messages.
|
SELF |
inHexadecimal()
Enable hexadecimal object representation of Iterable elements instead of standard java representation in error
messages.
|
void |
isEmpty()
Verifies that the actual group of values is empty.
|
SELF |
isNotEmpty()
Verifies that the actual group of values is not empty.
|
void |
isNullOrEmpty()
Verifies that the actual group of values is
null or empty. |
SELF |
isSorted()
Verifies that the actual array is sorted in ascending order according to the natural ordering of its elements.
|
SELF |
isSortedAccordingTo(Comparator<? super ELEMENT> comparator)
Verifies that the actual array is sorted according to the given comparator.
Empty arrays are considered sorted whatever the comparator is. One element arrays are considered sorted if the element is compatible with comparator, otherwise an AssertionError is thrown. |
SELF |
isSubsetOf(ELEMENT... values)
Verifies that all elements of actual are present in the given values.
|
SELF |
isSubsetOf(Iterable<? extends ELEMENT> values)
Verifies that all elements of actual are present in the given
Iterable. |
protected SELF |
isSubsetOfForProxy(ELEMENT[] values) |
protected String |
navigationDescription(String propertyName) |
protected <E> AbstractListAssert<?,List<? extends E>,E,ObjectAssert<E>> |
newListAssertInstance(List<? extends E> newActual)
Create a friendly soft or "hard" assertion.
|
protected abstract SELF |
newObjectArrayAssert(ELEMENT[] array) |
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 |
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) |
ObjectAssert<ELEMENT> |
singleElement()
Verifies that the array under test contains a single element and allows to perform assertions on that element.
|
<ASSERT extends AbstractAssert<?,?>> |
singleElement(InstanceOfAssertFactory<?,ASSERT> assertFactory)
Verifies that the array 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. |
SELF |
startsWith(ELEMENT... sequence)
Verifies that the actual array starts with the given sequence of objects, without any other objects between them.
|
protected SELF |
startsWithForProxy(ELEMENT[] sequence) |
<C> SELF |
usingComparatorForElementFieldsWithNames(Comparator<C> 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
|
<C> SELF |
usingComparatorForElementFieldsWithType(Comparator<C> comparator,
Class<C> type)
Deprecated.
This method is used with
usingFieldByFieldElementComparator() which is deprecated in favor of
usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration) or usingRecursiveComparison().
When using
and when using
|
<C> SELF |
usingComparatorForType(Comparator<C> comparator,
Class<C> type)
Allows to set a specific comparator for the given type of elements or their fields.
|
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. |
<OTHER_ELEMENT> |
zipSatisfy(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, describedAs, descriptionText, doesNotHave, doesNotHaveSameClassAs, doesNotHaveSameHashCodeAs, doesNotHaveToString, equals, extracting, extracting, failure, failureWithActualExpected, failWithActualExpectedAndMessage, failWithMessage, getWritableAssertionInfo, has, hashCode, hasSameClassAs, hasSameHashCodeAs, hasToString, is, isElementOfCustomAssert, isEqualTo, isExactlyInstanceOf, isIn, isIn, isInstanceOf, isInstanceOfAny, isInstanceOfSatisfying, isNot, isNotEqualTo, isNotExactlyInstanceOf, isNotIn, isNotIn, isNotInstanceOf, isNotInstanceOfAny, isNotNull, isNotOfAnyClassIn, isNotSameAs, isNull, isOfAnyClassIn, isSameAs, matches, matches, overridingErrorMessage, overridingErrorMessage, satisfies, satisfies, satisfies, satisfiesAnyOf, satisfiesAnyOf, satisfiesAnyOfForProxy, satisfiesForProxy, setCustomRepresentation, setDescriptionConsumer, setPrintAssertionsDescription, throwAssertionError, usingComparator, usingComparator, usingDefaultComparator, withFailMessage, withFailMessage, withRepresentation, withThreadDumpOnErrorclone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitas, describedAspublic 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 AbstractObjectArrayAssert<SELF,ELEMENT>>description - the new description to set.this object.Descriptable.describedAs(Description)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 AbstractObjectArrayAssert<SELF,ELEMENT>>description - the new description to set.args - optional parameter if description is a format String.this object.Descriptable.describedAs(String, Object...)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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>AssertionError - if the actual group of values is not null or not empty.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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>AssertionError - if the actual group of values is not empty.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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>this assertion object.AssertionError - if the actual group of values is empty.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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>expected - the expected number of values in the actual group.this assertion object.AssertionError - if the number of values of the actual group is not equal to the given one.public SELF hasSizeGreaterThan(int boundary)
Example:
// assertion will pass
assertThat(new String[] { "a", "b" }).hasSizeGreaterThan(1);
// assertion will fail
assertThat(new String[] { "a", "b" }).hasSizeGreaterThan(2);hasSizeGreaterThan in interface EnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>boundary - the given value to compare the actual size to.this assertion object.AssertionError - if the number of values of the actual array is not greater than the boundary.public SELF hasSizeGreaterThanOrEqualTo(int boundary)
Example:
// assertion will pass
assertThat(new String[] { "a", "b" }).hasSizeGreaterThanOrEqualTo(1)
.hasSizeGreaterThanOrEqualTo(2);
// assertion will fail
assertThat(new String[] { "a", "b" }).hasSizeGreaterThanOrEqualTo(3);hasSizeGreaterThanOrEqualTo in interface EnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>boundary - the given value to compare the actual size to.this assertion object.AssertionError - if the number of values of the actual array is not greater than or equal to the boundary.public SELF hasSizeLessThan(int boundary)
Example:
// assertion will pass
assertThat(new String[] { "a", "b" }).hasSizeLessThan(5);
// assertion will fail
assertThat(new String[] { "a", "b" }).hasSizeLessThan(2);hasSizeLessThan in interface EnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>boundary - the given value to compare the actual size to.this assertion object.AssertionError - if the number of values of the actual array is not less than the boundary.public SELF hasSizeLessThanOrEqualTo(int boundary)
Example:
// assertions will pass
assertThat(new String[] { "a", "b" }).hasSizeLessThanOrEqualTo(3)
.hasSizeLessThanOrEqualTo(2);
// assertion will fail
assertThat(new String[] { "a", "b" }).hasSizeLessThanOrEqualTo(1);hasSizeLessThanOrEqualTo in interface EnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>boundary - the given value to compare the actual size to.this assertion object.AssertionError - if the number of values of the actual array is not less than or equal to the boundary.public SELF hasSizeBetween(int lowerBoundary, int higherBoundary)
Example:
// assertions will pass
assertThat(new String[] { "a", "b" }).hasSizeBetween(0, 3)
.hasSizeBetween(2, 2);
// assertions will fail
assertThat(new String[] { "a", "b" }).hasSizeBetween(3, 4);hasSizeBetween in interface EnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,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 array is not between the boundaries.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};
int[] fourFiveSix = {4, 5, 6};
int[] sevenEight = {7, 8};
// assertion will pass
assertThat(oneTwoThree).hasSameSizeAs(fourFiveSix);
// assertion will fail
assertThat(oneTwoThree).hasSameSizeAs(sevenEight);hasSameSizeAs in interface EnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>other - the array to compare size with actual array.this assertion object.AssertionError - if the actual array is null.AssertionError - if the array parameter is null or is not a true array.AssertionError - if actual array and given array don't have the same size.public SELF hasSameSizeAs(Iterable<?> other)
Iterable.
Example:
int[] oneTwoThree = {1, 2, 3};
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass
assertThat(oneTwoThree).hasSameSizeAs(elvesRings);
// assertion will fail
assertThat(oneTwoThree).hasSameSizeAs(Arrays.asList("a", "b"));hasSameSizeAs in interface EnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>other - the Iterable to compare size with actual array.this assertion object.AssertionError - if the actual array is null.AssertionError - if the other Iterable is null.AssertionError - if actual array and given Iterable don't have the same size.@SafeVarargs public final SELF contains(ELEMENT... values)
Example :
String[] abc = {"a", "b", "c"};
// assertions will pass
assertThat(abc).contains("b", "a");
assertThat(abc).contains("b", "a", "b");
// assertions will fail
assertThat(abc).contains("d");
assertThat(abc).contains("c", "d");contains in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the given values.this assertion object.NullPointerException - if the given argument is null.IllegalArgumentException - if the given argument is an empty array.AssertionError - if the actual array is null.AssertionError - if the actual array does not contain the given values.@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 matter String[] abc = {"a", "b", "c"};
// assertions succeed
assertThat(abc).containsOnly("c", "b", "a");
// duplicates are ignored
assertThat(abc).containsOnly("a", "a", "b", "c", "c");
// ... on both actual and expected values
assertThat(new String[] { "a", "a", "b" }).containsOnly("a", "b")
.containsOnly("a", "a", "b", "b");
// assertion will fail because the given values do not contain "c"
assertThat(abc).containsOnly("a", "b");
// assertion will fail because abc does not contain "d"
assertThat(abc).containsOnly("a", "b", "c", "d");containsOnly in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the given values.this assertion object.NullPointerException - if the given argument is null.IllegalArgumentException - if the given argument is an empty array.AssertionError - if the actual array is null.AssertionError - if the actual array does not contain the given values, i.e. the actual array contains some
or none of the given values, or the actual array contains more values than the given ones.public SELF containsOnlyElementsOf(Iterable<? extends ELEMENT> iterable)
containsOnly(Object[]) : verifies that actual contains all 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).
Example :
Ring[] rings = {nenya, vilya};
// assertions will pass
assertThat(rings).containsOnlyElementsOf(newArrayList(nenya, vilya));
assertThat(rings).containsOnlyElementsOf(newArrayList(nenya, nenya, vilya, vilya));
assertThat(newArrayList(nenya, nenya, vilya, vilya)).containsOnlyElementsOf(rings);
// assertion will fail as actual does not contain narya
assertThat(rings).containsOnlyElementsOf(newArrayList(nenya, vilya, narya));
// assertion will fail as actual contains nenya
assertThat(rings).containsOnlyElementsOf(newArrayList(vilya));containsOnlyElementsOf in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>iterable - the given Iterable we will get elements from.this assertion object.public SELF containsOnlyNulls()
Example :
Person[] persons1 = {null, null, null};
Person[] persons2 = {null, null, person};
// assertion will pass
assertThat(persons1).containsOnlyNulls();
// assertions will fail
assertThat(persons2).containsOnlyNulls();
assertThat(new Person[0]).containsOnlyNulls();containsOnlyNulls in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>this assertion object.AssertionError - if the actual array is null.AssertionError - if the actual array is empty or contains a non null elementpublic SELF hasOnlyOneElementSatisfying(Consumer<? super ELEMENT> elementAssertions)
Consumer,
if it does not, only the first error is reported, use SoftAssertions to get all the errors.
Example:
Jedi[] jedis = array(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 = array(new Jedi("Yoda", "red"), new Jedi("Luke", "green"));
assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("Yo"));hasOnlyOneElementSatisfying in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>elementAssertions - the assertions to perform on the unique element.this assertion object.AssertionError - if the array does not have a unique element.AssertionError - if the array's unique element does not satisfies the given assertions.public SELF hasSameElementsAs(Iterable<? extends ELEMENT> iterable)
containsOnlyElementsOf(Iterable) : verifies that actual contains all elements of the
given Iterable and nothing else, in any order.
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertions will pass:
assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya, vilya));
assertThat(elvesRings).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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>iterable - the Iterable whose elements we expect to be presentAssertionError - if the actual array is nullNullPointerException - if the given Iterable is nullAssertionError - if the actual Iterable does not have the same elements, in any order, as the given
Iterable@SafeVarargs public final SELF containsOnlyOnce(ELEMENT... values)
Examples :
// array is a factory method to create arrays.
// assertions will pass
assertThat(array("winter", "is", "coming")).containsOnlyOnce("winter");
assertThat(array("winter", "is", "coming")).containsOnlyOnce("coming", "winter");
// assertions will fail
assertThat(array("winter", "is", "coming")).containsOnlyOnce("Lannister");
assertThat(array("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark");
assertThat(array("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark", "Lannister", "Arya");containsOnlyOnce in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the given values.this assertion object.NullPointerException - if the given argument is null.IllegalArgumentException - if the given argument is an empty array.AssertionError - if the actual array is null.AssertionError - if the actual array does not contain the given values, i.e. the actual array contains some
or none of the given values, or the actual array contains more than once these values.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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>iterable - the given Iterable we will get elements from.this assertion object.@SafeVarargs public final SELF containsExactly(ELEMENT... values)
Example :
Ring[] elvesRings = {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);containsExactly in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the given values.this assertion object.NullPointerException - if the given argument is null.AssertionError - if the actual array is null.AssertionError - if the actual array does not contain the given values with same order, i.e. the actual array
contains some or none of the given values, or the actual array contains more values than the given ones
or values are the same but the order is not.@SafeVarargs public final SELF containsExactlyInAnyOrder(ELEMENT... values)
Example :
Ring[] elvesRings = {vilya, nenya, narya, vilya};
// assertion will pass
assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);
// assertion will fail as vilya exists twice in elvesRings
assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);containsExactlyInAnyOrder in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the given values.this assertion object.NullPointerException - if the given argument is null.AssertionError - if the actual array is null.AssertionError - if the actual arrray does not contain the given values, i.e. the actual array
contains some or none of the given values, or the actual array contains more values than the given ones.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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the given values.this assertion object.public SELF containsExactlyElementsOf(Iterable<? extends ELEMENT> iterable)
containsExactly(Object...) but handles the Iterable to array conversion : verifies that
actual contains exactly the elements of the given Iterable and nothing else in the same order.
Example :
Ring[] elvesRings = {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));containsExactlyElementsOf in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>iterable - the given Iterable we will get elements from.this assertion object.@SafeVarargs public final SELF containsSequence(ELEMENT... sequence)
Use containsSubsequence(Object...) to allow values between the expected sequence values.
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertion will pass
assertThat(elvesRings).containsSequence(vilya, nenya);
assertThat(elvesRings).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);containsSequence in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>sequence - the sequence of objects to look for.AssertionError - if the actual array is null.AssertionError - if the given array is null.AssertionError - if the actual array does not contain the given sequence.public SELF containsSequence(Iterable<? extends ELEMENT> sequence)
Use containsSubsequence(Iterable) to allow values between the expected sequence values.
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertion will pass
assertThat(elvesRings).containsSequence(newArrayList(vilya, nenya));
assertThat(elvesRings).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));containsSequence in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>sequence - the sequence of objects to look for.AssertionError - if the actual array is null.AssertionError - if the given array is null.AssertionError - if the actual array does not contain the given sequence.@SafeVarargs public final SELF doesNotContainSequence(ELEMENT... sequence)
Use doesNotContainSubsequence(Object...) to also ensure the sequence does not exist with values between the expected sequence values.
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertion will pass, the elements order is correct but there is a value between them (nenya)
assertThat(elvesRings).containsSequence(vilya, narya);
assertThat(elvesRings).containsSequence(nenya, vilya);
// assertions will fail
assertThat(elvesRings).containsSequence(vilya, nenya);
assertThat(elvesRings).containsSequence(nenya, narya);doesNotContainSequence in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>sequence - the sequence of objects to look for.AssertionError - if the actual array is null.AssertionError - if the given array is null.AssertionError - if the actual array does not contain the given sequence.public SELF doesNotContainSequence(Iterable<? extends ELEMENT> sequence)
Use doesNotContainSubsequence(Object...) to also ensure the sequence does not exist with values between the expected sequence values.
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertion will pass, 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));
// assertions will fail
assertThat(elvesRings).containsSequence(newArrayList(vilya, nenya));
assertThat(elvesRings).containsSequence(newArrayList(nenya, narya));doesNotContainSequence in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>sequence - the sequence of objects to look for.AssertionError - if the actual array is null.AssertionError - if the given array is null.AssertionError - if the actual array does not contain the given sequence.@SafeVarargs public final SELF containsSubsequence(ELEMENT... subsequence)
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertions will pass
assertThat(elvesRings).containsSubsequence(vilya, nenya);
assertThat(elvesRings).containsSubsequence(vilya, narya);
// assertion will fail
assertThat(elvesRings).containsSubsequence(nenya, vilya);containsSubsequence in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>subsequence - the subsequence of objects to look for.AssertionError - if the actual array is null.AssertionError - if the given array is null.AssertionError - if the actual array does not contain the given subsequence.public SELF containsSubsequence(Iterable<? extends ELEMENT> subsequence)
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertions will pass
assertThat(elvesRings).containsSubsequence(newArrayList(vilya, nenya));
assertThat(elvesRings).containsSubsequence(newArrayList(vilya, narya));
// assertion will fail
assertThat(elvesRings).containsSubsequence(newArrayList(nenya, vilya));containsSubsequence in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>subsequence - the subsequence of objects to look for.AssertionError - if the actual array is null.AssertionError - if the given array is null.AssertionError - if the actual array does not contain the given subsequence.@SafeVarargs public final SELF doesNotContainSubsequence(ELEMENT... subsequence)
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertions will pass
assertThat(elvesRings).doesNotContainSubsequence(nenya, vilya);
// assertion will fail
assertThat(elvesRings).doesNotContainSubsequence(vilya, nenya);
assertThat(elvesRings).doesNotContainSubsequence(vilya, narya);doesNotContainSubsequence in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>subsequence - the subsequence of objects to look for.AssertionError - if the actual array is null.AssertionError - if the given array is null.AssertionError - if the actual array contains the given subsequence.protected SELF doesNotContainSubsequenceForProxy(ELEMENT[] subsequence)
public SELF doesNotContainSubsequence(Iterable<? extends ELEMENT> subsequence)
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertions will pass
assertThat(elvesRings).doesNotContainSubsequence(newArrayList(nenya, vilya));
// assertion will fail
assertThat(elvesRings).doesNotContainSubsequence(newArrayList(vilya, nenya));
assertThat(elvesRings).doesNotContainSubsequence(newArrayList(vilya, narya));doesNotContainSubsequence in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>subsequence - the subsequence of objects to look for.AssertionError - if the actual array is null.AssertionError - if the given array is null.AssertionError - if the actual array contains the given subsequence.public SELF contains(ELEMENT value, Index index)
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertions will pass
assertThat(elvesRings).contains(vilya, atIndex(0));
assertThat(elvesRings).contains(nenya, atIndex(1));
assertThat(elvesRings).contains(narya, atIndex(2));
// assertions will fail
assertThat(elvesRings).contains(vilya, atIndex(1));
assertThat(elvesRings).contains(nenya, atIndex(2));
assertThat(elvesRings).contains(narya, atIndex(0));contains in interface IndexedObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>value - the object to look for.index - the index where the object should be stored in the actual array.AssertionError - if the actual array is null or empty.NullPointerException - if the given Index is null.IndexOutOfBoundsException - if the value of the given Index is equal to or greater than the size of the actual
group.AssertionError - if the actual array does not contain the given object at the given index.public SELF hasOnlyElementsOfTypes(Class<?>... types)
Example :
Object[] objects = { "foo", new StringBuilder() };
// assertions will pass
assertThat(objects).hasOnlyElementsOfTypes(CharSequence.class);
assertThat(objects).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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>types - the expected classes and interfacesthis assertion object.NullPointerException - if the given argument is null.AssertionError - if the actual array is null.AssertionError - if not all elements of the actual array are instances of one of the given typespublic SELF hasExactlyElementsOfTypes(Class<?>... expectedTypes)
Example:
Object[] objects = { 1, "a", "b", 1.00 };
// assertion succeeds
assertThat(objects).hasExactlyElementsOfTypes(Integer.class, String.class, String.class, Double.class);
// assertions fail
// missing second String type
assertThat(objects).hasExactlyElementsOfTypes(Integer.class, String.class, Double.class);
// no Float type in actual
assertThat(objects).hasExactlyElementsOfTypes(Float.class, String.class, String.class, Double.class);
// correct types but wrong order
assertThat(objects).hasExactlyElementsOfTypes(String.class, Integer.class, String.class, Double.class);
// actual has more elements than the specified expected types
assertThat(objects).hasExactlyElementsOfTypes(String.class);hasExactlyElementsOfTypes in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>expectedTypes - the expected typesthis assertion object.NullPointerException - if the given type array is null.AssertionError - if actual is null.AssertionError - if the actual elements types don't exactly match the given ones (in the given order).public SELF doesNotContain(ELEMENT value, Index index)
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertions will pass
assertThat(elvesRings).doesNotContain(vilya, atIndex(1));
assertThat(elvesRings).doesNotContain(nenya, atIndex(2));
assertThat(elvesRings).doesNotContain(narya, atIndex(0));
// assertions will fail
assertThat(elvesRings).doesNotContain(vilya, atIndex(0));
assertThat(elvesRings).doesNotContain(nenya, atIndex(1));
assertThat(elvesRings).doesNotContain(narya, atIndex(2));doesNotContain in interface IndexedObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>value - the object to look for.index - the index where the object should not be stored in the actual array.AssertionError - if the actual array is null.NullPointerException - if the given Index is null.AssertionError - if the actual array contains the given object at the given index.@SafeVarargs public final SELF doesNotContain(ELEMENT... values)
Example :
String[] abc = {"a", "b", "c"};
// assertion will pass
assertThat(abc).doesNotContain("d", "e");
// assertions will fail
assertThat(abc).doesNotContain("a");
assertThat(abc).doesNotContain("a", "b", "c");
assertThat(abc).doesNotContain("a", "x");doesNotContain in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the given values.this assertion object.NullPointerException - if the given argument is null.IllegalArgumentException - if the given argument is an empty array.AssertionError - if the actual array is null.AssertionError - if the actual array contains any of the given values.public SELF doesNotContainAnyElementsOf(Iterable<? extends ELEMENT> iterable)
Iterable (i.e. none).
Example:
String[] abc = {"a", "b", "c"};
// assertion will pass
assertThat(actual).doesNotContainAnyElementsOf(newArrayList("d", "e"));
// assertions will fail
assertThat(actual).doesNotContainAnyElementsOf(newArrayList("a", "b"));
assertThat(actual).doesNotContainAnyElementsOf(newArrayList("d", "e", "a"));doesNotContainAnyElementsOf in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>iterable - the Iterable whose elements must not be in the actual array.this assertion object.NullPointerException - if the given argument is null.IllegalArgumentException - if the given argument is an empty iterable.AssertionError - if the actual array is null.AssertionError - if the actual array contains some elements of the given Iterable.public SELF doesNotHaveDuplicates()
Example :
String[] abc = {"a", "b", "c"};
String[] lotsOfAs = {"a", "a", "a"};
// assertion will pass
assertThat(abc).doesNotHaveDuplicates();
// assertion will fail
assertThat(lotsOfAs).doesNotHaveDuplicates();doesNotHaveDuplicates in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>this assertion object.AssertionError - if the actual array is null.AssertionError - if the actual array contains duplicates.@SafeVarargs public final SELF startsWith(ELEMENT... sequence)
containsSequence(Object...), but it also verifies that the first element in the
sequence is also the first element of the actual array.
Example :
String[] abc = {"a", "b", "c"};
// assertion will pass
assertThat(abc).startsWith("a", "b");
// assertion will fail
assertThat(abc).startsWith("c");startsWith in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>sequence - the sequence of objects to look for.NullPointerException - if the given argument is null.IllegalArgumentException - if the given argument is an empty array.AssertionError - if the actual array is null.AssertionError - if the actual array does not start with the given sequence of objects.public SELF endsWith(ELEMENT[] sequence)
containsSequence(Object...), but it also verifies that the last element in the
sequence is also last element of the actual array.
Example :
String[] abc = {"a", "b", "c"};
// assertions will pass
assertThat(abc).endsWith(new String[0])
.endsWith(new String[] {"b", "c"});
// assertion will fail
assertThat(abc).endsWith(new String[] {"a"});endsWith in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>sequence - the sequence of objects to look for.NullPointerException - if the given argument is null.AssertionError - if the actual array is null.AssertionError - if the actual array does not end with the given sequence of objects.@SafeVarargs public final SELF endsWith(ELEMENT first, ELEMENT... sequence)
containsSequence(Object...), but it also verifies that the last element in the
sequence is also last element of the actual array.
Example :
String[] abc = {"a", "b", "c"};
// assertion will pass
assertThat(abc).endsWith("b", "c");
// assertion will fail
assertThat(abc).endsWith("a");endsWith in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>first - the first element of the end sequence of objects to look for.sequence - the rest of the end sequence of objects to look for.NullPointerException - if the given argument is null.AssertionError - if the actual array is null.AssertionError - if the actual array does not end with the given sequence of objects.public SELF isSubsetOf(Iterable<? extends ELEMENT> values)
Iterable.
Example:
Ring[] elvesRings = {vilya, nenya, narya};
List<Ring> ringsOfPower = newArrayList(oneRing, vilya, nenya, narya, dwarfRing, manRing);
// assertion will pass:
assertThat(elvesRings).isSubsetOf(ringsOfPower);
// assertion will fail:
assertThat(elvesRings).isSubsetOf(newArrayList(nenya, narya));isSubsetOf in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the Iterable that should contain all actual elements.AssertionError - if the actual Iterable is null.NullPointerException - if the given Iterable is null.AssertionError - if the actual Iterable is not subset of set Iterable.@SafeVarargs public final SELF isSubsetOf(ELEMENT... values)
Example:
Ring[] elvesRings = {vilya, nenya, narya};
// assertions will pass:
assertThat(elvesRings).isSubsetOf(vilya, nenya, narya);
assertThat(elvesRings).isSubsetOf(vilya, nenya, narya, dwarfRing);
// assertions will fail:
assertThat(elvesRings).isSubsetOf(vilya, nenya);
assertThat(elvesRings).isSubsetOf(vilya, nenya, dwarfRing);isSubsetOf in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the values that should be used for checking the elements of actual.AssertionError - if the actual Iterable is null.AssertionError - if the actual Iterable is not subset of the given values.public SELF containsNull()
Example :
String[] abc = {"a", "b", "c"};
String[] abNull = {"a", "b", null};
// assertion will pass
assertThat(abNull).containsNull();
// assertion will fail
assertThat(abc).containsNull();containsNull in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>this assertion object.AssertionError - if the actual array is null.AssertionError - if the actual array does not contain a null element.public SELF doesNotContainNull()
Example :
String[] abc = {"a", "b", "c"};
String[] abNull = {"a", "b", null};
// assertion will pass
assertThat(abc).doesNotContainNull();
// assertion will fail
assertThat(abNull).doesNotContainNull();doesNotContainNull in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>this assertion object.AssertionError - if the actual array is null.AssertionError - if the actual array contains a null element.public SELF are(Condition<? super ELEMENT> condition)
Example :
String[] abc = {"a", "b", "c"};
String[] abcc = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>condition - the given condition.this object.NullPointerException - if the given condition is null.AssertionError - if an element cannot be cast to ELEMENT.AssertionError - if one or more elements don't satisfy the given condition.public SELF areNot(Condition<? super ELEMENT> condition)
Example :
String[] abc = {"a", "b", "c"};
String[] abcc = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>condition - the given condition.this object.NullPointerException - if the given condition is null.AssertionError - if an element cannot be cast to ELEMENT.AssertionError - if one or more elements satisfy the given condition.public SELF have(Condition<? super ELEMENT> condition)
Example :
String[] abc = {"a", "b", "c"};
String[] abcc = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>condition - the given condition.this object.NullPointerException - if the given condition is null.AssertionError - if an element cannot be cast to ELEMENT.AssertionError - if one or more elements do not satisfy the given condition.public SELF doNotHave(Condition<? super ELEMENT> condition)
Example :
String[] abc = {"a", "b", "c"};
String[] abcc = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>condition - the given condition.this object.NullPointerException - if the given condition is null.AssertionError - if an element cannot be cast to ELEMENT.AssertionError - if one or more elements satisfy the given condition.public SELF areAtLeast(int times, Condition<? super ELEMENT> condition)
Example :
int[] oneTwoThree = {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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>times - the minimum number of times the condition should be verified.condition - the given condition.this object.NullPointerException - if the given condition is null.AssertionError - if an element can not be cast to T.AssertionError - if the number of elements satisfying the given condition is < n.public SELF areAtLeastOne(Condition<? super ELEMENT> condition)
This method is an alias for areAtLeast(1, condition).
Example:
// jedi is a Condition<String>
assertThat(new String[]{"Luke", "Solo", "Leia"}).areAtLeastOne(jedi);areAtLeastOne in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>condition - the given condition.this assertion object.haveAtLeast(int, Condition)public SELF areAtMost(int times, Condition<? super ELEMENT> condition)
Example :
int[] oneTwoThree = {1, 2, 3};
Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number");
// assertions will pass
oneTwoThree.areAtMost(2, oddNumber);
oneTwoThree.areAtMost(3, oddNumber);
// assertion will fail
oneTwoThree.areAtMost(1, oddNumber);areAtMost in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>times - the number of times the condition should be at most verified.condition - the given condition.this object.NullPointerException - if the given condition is null.AssertionError - if an element cannot be cast to ELEMENT.AssertionError - if the number of elements satisfying the given condition is > n.public SELF areExactly(int times, Condition<? super ELEMENT> condition)
Example :
int[] oneTwoThree = {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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>times - the exact number of times the condition should be verified.condition - the given condition.this object.NullPointerException - if the given condition is null.AssertionError - if an element cannot be cast to ELEMENT.AssertionError - if the number of elements satisfying the given condition is ≠ n.public SELF haveAtLeastOne(Condition<? super ELEMENT> condition)
This method is an alias for haveAtLeast(1, condition).
Example:
BasketBallPlayer[] bullsPlayers = {butler, rose};
// potentialMvp is a Condition<BasketBallPlayer>
assertThat(bullsPlayers).haveAtLeastOne(potentialMvp);haveAtLeastOne in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>condition - the given condition.this assertion object.haveAtLeast(int, Condition)public SELF haveAtLeast(int times, Condition<? super ELEMENT> condition)
Example :
int[] oneTwoThree = {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 areAtLeast(int, Condition).haveAtLeast in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,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 :
int[] oneTwoThree = {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 areAtMost(int, Condition).haveAtMost in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,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 :
int[] oneTwoThree = {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 areExactly(int, Condition).haveExactly in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>times - the exact number of times the condition must hold.condition - the given condition.this assertion object.public SELF hasAtLeastOneElementOfType(Class<?> type)
Object group has the specified type (matching
includes subclasses of the given type).
Example:
Number[] numbers = { 2, 6L, 8.0 };
// successful assertion:
assertThat(numbers).hasAtLeastOneElementOfType(Long.class);
// assertion failure:
assertThat(numbers).hasAtLeastOneElementOfType(Float.class);hasAtLeastOneElementOfType in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>type - the expected type.public SELF hasOnlyElementsOfType(Class<?> type)
Object group belong to the specified type (matching includes
subclasses of the given type).
Example:
Number[] numbers = { 2, 6, 8 };
// successful assertion:
assertThat(numbers).hasOnlyElementsOfType(Integer.class);
// assertion failure:
assertThat(numbers).hasOnlyElementsOfType(Long.class);hasOnlyElementsOfType in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>type - the expected type.public SELF doesNotHaveAnyElementsOfTypes(Class<?>... unexpectedTypes)
Object group do not belong to the specified types (including subclasses).
Example:
Number[] numbers = { 2, 6, 8.0 };
// successful assertion:
assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Float.class);
// assertion failure:
assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Integer.class);doesNotHaveAnyElementsOfTypes in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>unexpectedTypes - the not expected types.public SELF isSorted()
All array elements must be primitive or implement the Comparable interface and must be mutually comparable (that is,
e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array), examples :
isSorted in interface ArraySortedAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>this assertion object.public SELF isSortedAccordingTo(Comparator<? super ELEMENT> comparator)
isSortedAccordingTo in interface ArraySortedAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>comparator - the Comparator used to compare array elementsthis assertion object.public SELF containsAll(Iterable<? extends ELEMENT> iterable)
Iterable, in any order.
Example :
String[] abc = {"a", "b", "c"};
// assertion will pass
assertThat(abc).containsAll(Arrays.asList("b", "c"));
// assertions will fail
assertThat(abc).containsAll(Arrays.asList("d"));
assertThat(abc).containsAll(Arrays.asList("a", "b", "c", "d"));containsAll in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>iterable - the given Iterable we will get elements from.this assertion object.NullPointerException - if the given argument is null.AssertionError - if the actual array is null.AssertionError - if the actual array does not contain all the elements of given Iterable.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(invoiceArray).usingComparator(invoicePayeeComparator).isEqualTo(expectedinvoiceArray).
// compares invoices by date, doesNotHaveDuplicates and contains both use the given invoice date comparator
assertThat(invoiceArray).usingComparator(invoiceDateComparator).doesNotHaveDuplicates().contains(may2010Invoice)
// as assertThat(invoiceArray) creates a new assertion, it falls back to standard comparison strategy
// based on Invoice's equal method to compare invoiceArray elements to lowestInvoice.
assertThat(invoiceArray).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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>elementComparator - the comparator to use for incoming assertion checks.this assertion object.NullPointerException - if the given comparator is null.public SELF usingDefaultElementComparator()
This method should be used to disable a custom comparison strategy set by calling
EnumerableAssert.usingElementComparator(Comparator).
usingDefaultElementComparator in interface EnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>this assertion object.@Deprecated public <C> SELF usingComparatorForElementFieldsWithNames(Comparator<C> 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...)usingRecursiveFieldByFieldElementComparator()
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;
}
};
TolkienCharacter[] hobbits = new TolkienCharacter[] {frodo};
// assertions will pass
assertThat(hobbits).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingFieldByFieldElementComparator()
.contains(tallerFrodo);
assertThat(hobbits).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingElementComparatorOnFields("height")
.contains(tallerFrodo);
assertThat(hobbits).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingElementComparatorIgnoringFields("name")
.contains(tallerFrodo);
assertThat(hobbits).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingRecursiveFieldByFieldElementComparator()
.contains(tallerFrodo);
// assertion will fail
assertThat(hobbits).usingComparatorForElementFieldsWithNames(closeEnough, "height")
.usingFieldByFieldElementComparator()
.containsExactly(reallyTallFrodo);C - 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 <C> SELF usingComparatorForElementFieldsWithType(Comparator<C> comparator, Class<C> 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(String...)usingElementComparatorIgnoringFields(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;
}
};
TolkienCharacter[] hobbits = new TolkienCharacter[] {frodo};
// assertions will pass
assertThat(hobbits).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingFieldByFieldElementComparator()
.contains(tallerFrodo);
assertThat(hobbits).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingElementComparatorOnFields("height")
.contains(tallerFrodo);
assertThat(hobbits).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingElementComparatorIgnoringFields("name")
.contains(tallerFrodo);
assertThat(hobbits).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingRecursiveFieldByFieldElementComparator()
.contains(tallerFrodo);
// assertion will fail
assertThat(hobbits).usingComparatorForElementFieldsWithType(closeEnough, Double.class)
.usingFieldByFieldElementComparator()
.contains(reallyTallFrodo);
If multiple compatible comparators have been registered for a given type, the closest in the inheritance
chain to the given type is chosen in the following order:
typetypetypeC - 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 <C> SELF usingComparatorForType(Comparator<C> comparator, Class<C> type)
usingComparatorForElementFieldsWithType(java.util.Comparator<C>, java.lang.Class<C>) by applying comparator specified for given type
to elements themselves, not only to their fields.
Usage of this method affects comparators set by the following methods:
usingFieldByFieldElementComparator()usingElementComparatorOnFields(String...)usingElementComparatorIgnoringFields(String...)Example:
Person obiwan = new Person("Obi-Wan");
obiwan.setHeight(new BigDecimal("1.820"));
// assertion will pass
assertThat(obiwan).extracting("name", "height")
.usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class)
.containsExactly("Obi-Wan", new BigDecimal("1.82"));C - 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.
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.
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(array(frodo)).contains(frodoClone);
// frodo and frodoClone are equals when doing a field by field comparison.
assertThat(array(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.AbstractIterableAssert.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);
Doctor[] doctors = array(drSheldon, drLeonard, drRaj);
Person[] people = array(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.AbstractIterableAssert.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);
Doctor[] doctors = array(drSheldon, drLeonard, drRaj);
Person[] people = array(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.
A 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.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.
Example:
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(array(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK
// ... but not when comparing both name and race
assertThat(array(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAILfields - the name of the fields to use the element comparator onthis 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(array(derrickRose)).usingRecursiveFieldByFieldElementComparatorOnFields("name.last", "team", "nickname.first")
.contains(jalenRose);
// assertion fails, name.first values differ
assertThat(array(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(array(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-comparison@Deprecated public SELF usingElementComparatorIgnoringFields(String... fields)
usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...) instead.
Use field/property by field/property 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.
Example:
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(array(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK
// ... but not when comparing both name and race
assertThat(array(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAILfields - the name of the fields to ignorethis 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(array(derrickRose)).usingRecursiveFieldByFieldElementComparatorIgnoringFields("name.first", "nickname.last")
.contains(jalenRose);
// assertion fails, names are ignored but nicknames are not and nickname.last values differ
assertThat(array(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(array(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 AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> extracting(String fieldOrProperty)
It allows you to test a field/property of the array'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 array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)
// they can be public field or properties, both works when extracting their values.
TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {
new TolkienCharacter("Frodo", 33, HOBBIT),
new TolkienCharacter("Sam", 38, HOBBIT),
new TolkienCharacter("Gandalf", 2020, MAIA),
new TolkienCharacter("Legolas", 1000, ELF),
new TolkienCharacter("Pippin", 28, HOBBIT),
new TolkienCharacter("Gimli", 139, DWARF),
new TolkienCharacter("Aragorn", 87, MAN,
new TolkienCharacter("Boromir", 37, MAN)
};
// let's verify the names of TolkienCharacter in fellowshipOfTheRing :
assertThat(fellowshipOfTheRing).extracting("name")
.contains("Boromir", "Gandalf", "Frodo")
.doesNotContain("Sauron", "Elrond");
// you can also extract nested field/property like the name of Race :
assertThat(fellowshipOfTheRing).extracting("race.name")
.contains("Hobbit", "Elf")
.doesNotContain("Orc");
A property with the given name is looked for first, if it does not exist then a field with the given name
is looked for.
Note that the order of extracted field/property values is consistent with the array order.
fieldOrProperty - the field/property to extract from the array under testIntrospectionError - if no field or property exists with the given namepublic <P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extracting(String fieldOrProperty, Class<P> extractingType)
It allows you to test a field/property of the array's elements instead of testing the elements themselves, which can be much less work !
Let's take an example to make things clearer :
// Build an array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)
// they can be public field or properties, both works when extracting their values.
TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {
new TolkienCharacter("Frodo", 33, HOBBIT),
new TolkienCharacter("Sam", 38, HOBBIT),
new TolkienCharacter("Gandalf", 2020, MAIA),
new TolkienCharacter("Legolas", 1000, ELF),
new TolkienCharacter("Pippin", 28, HOBBIT),
new TolkienCharacter("Gimli", 139, DWARF),
new TolkienCharacter("Aragorn", 87, MAN,
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 also extract nested field/property 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 does not exist then a field with the given name
is looked for.
Note that the order of extracted field/property values is consistent with the order of the array under test.
P - the type of elements to extract.fieldOrProperty - the field/property to extract from the array under testextractingType - type to returnIntrospectionError - if no field or property exists with the given namepublic AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> extracting(String... propertiesOrFields)
It allows you to test fields/properties of the array's elements instead of testing the elements themselves, it can be sometimes 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 array (the Tuple's data order is the same as the given fields/properties order).
Let's take an example to make things clearer :
// Build an array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)
// they can be public field or properties, both works when extracting their values.
TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {
new TolkienCharacter("Frodo", 33, HOBBIT),
new TolkienCharacter("Sam", 38, HOBBIT),
new TolkienCharacter("Gandalf", 2020, MAIA),
new TolkienCharacter("Legolas", 1000, ELF),
new TolkienCharacter("Pippin", 28, HOBBIT),
new TolkienCharacter("Gimli", 139, DWARF),
new TolkienCharacter("Aragorn", 87, MAN,
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 does not exist the a field with the given name is
looked for.
Note that the order of extracted property/field values is consistent with the iteration order of the array under test.
propertiesOrFields - the properties/fields to extract from the initial array under testIntrospectionError - if one of the given name does not match a field or property in one of the initial Iterable's element.public <U> AbstractListAssert<?,List<? extends U>,U,ObjectAssert<U>> extracting(Function<? super ELEMENT,U> extractor)
This method is similar to extracting(String) but more refactoring friendly as it does not use introspection.
Let's take a look 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.
TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {
new TolkienCharacter("Frodo", 33, HOBBIT),
new TolkienCharacter("Sam", 38, HOBBIT),
new TolkienCharacter("Gandalf", 2020, MAIA),
new TolkienCharacter("Legolas", 1000, ELF),
new TolkienCharacter("Pippin", 28, HOBBIT),
new TolkienCharacter("Gimli", 139, DWARF),
new TolkienCharacter("Aragorn", 87, MAN,
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.U - the type of elements to extract.extractor - the object 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 in safer way than by using extracting(String), as it
doesn't use introspection.
Let's take a look 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.
TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {
new TolkienCharacter("Frodo", 33, HOBBIT),
new TolkienCharacter("Sam", 38, HOBBIT),
new TolkienCharacter("Gandalf", 2020, MAIA),
new TolkienCharacter("Legolas", 1000, ELF),
new TolkienCharacter("Pippin", 28, HOBBIT),
new TolkienCharacter("Gimli", 139, DWARF),
new TolkienCharacter("Aragorn", 87, MAN,
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 array under test.
V - the type of elements to extract.EXCEPTION - the exception type of ThrowingExtractorextractor - the object transforming input object to desired one@SafeVarargs public final AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> extracting(Function<? super ELEMENT,?>... extractors)
Functions to extract the values from the array's elements into a new list
composed of Tuples (a simple data structure containing the extracted values), this new list becoming the
object under test.
It allows you to test values from the array's elements instead of testing the elements themselves, which sometimes can be much less work!
The Tuple data corresponds to the extracted values from the arrays's elements, for instance if you pass functions
extracting "id", "name" and "email" values then each Tuple's data will be composed of an id, a name and an email
extracted from the element of the initial array (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 an array of TolkienCharacter, a TolkienCharacter has a name (String) and a Race (a class)
// they can be public field or properties, both works when extracting their values.
TolkienCharacter[] fellowshipOfTheRing = new TolkienCharacter[] {
new TolkienCharacter("Frodo", 33, HOBBIT),
new TolkienCharacter("Sam", 38, HOBBIT),
new TolkienCharacter("Gandalf", 2020, MAIA),
new TolkienCharacter("Legolas", 1000, ELF),
new TolkienCharacter("Pippin", 28, HOBBIT),
new TolkienCharacter("Gimli", 139, DWARF),
new TolkienCharacter("Aragorn", 87, MAN,
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 array 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 array under test.protected AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> extractingForProxy(Function<? super ELEMENT,?>[] extractors)
public <V,C extends Collection<V>> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(Function<? super ELEMENT,C> extractor)
It allows testing the results of extracting values that are represented by Iterables.
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.addChildren(bart, lisa, maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
CartoonCharacter[] parents = new CartoonCharacter[] { homer, fred };
// check children
assertThat(parents).flatExtracting(CartoonCharacter::getChildren)
.containsOnly(bart, lisa, maggie, pebbles);
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted
collections.V - the type of elements to extract.C - the type of collection to flat/extract.extractor - the object transforming input object to an Iterable of desired onespublic <V,C extends Collection<V>,EXCEPTION extends Exception> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(ThrowingExtractor<? super ELEMENT,C,EXCEPTION> extractor)
It allows testing the results of extracting values that are represented by Iterables.
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.addChildren(bart, lisa, maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
CartoonCharacter[] parents = new CartoonCharacter[] { homer, fred };
// check children
assertThat(parents).flatExtracting(input -> {
if (input.getChildren().size() == 0) {
throw new Exception("no children");
}
return input.getChildren();
}).containsOnly(bart, lisa, maggie, pebbles);
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted
collections.V - the type of elements to extract.C - the type of collection to flat/extract.EXCEPTION - the exception type of ThrowingExtractorextractor - the object transforming input object to an Iterable of desired onespublic AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(String propertyName)
It allows testing the elements of extracting values that are represented by 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.addChildren(bart, lisa, maggie);
CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
fred.getChildren().add(pebbles);
CartoonCharacter[] parents = new CartoonCharacter[] { homer, fred };
// check children
assertThat(parents).flatExtracting("children")
.containsOnly(bart, lisa, maggie, pebbles);
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted
collections.propertyName - 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.public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> extractingResultOf(String method)
It allows you to test a method results of the array's elements instead of testing the elements themselves, which can be much less work!
It is especially useful for classes that does 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 a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()
WesterosHouse[] greatHousesOfWesteros = new WesterosHouse[] { new WesterosHouse("Stark", "Winter is Coming"),
new WesterosHouse("Lannister", "Hear Me Roar!"), new WesterosHouse("Greyjoy", "We Do Not Sow"),
new WesterosHouse("Baratheon", "Our is the Fury"), new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"),
new WesterosHouse("Tyrell", "Growing Strong") };
// let's verify the words of the great houses of Westeros:
assertThat(greatHousesOfWesteros).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 values is consistent with the order of the array under test.
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> extractingType)
It allows you to test a method results of the array's elements instead of testing the elements themselves, which can be much less work!
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 a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()
WesterosHouse[] greatHousesOfWesteros = new WesterosHouse[] { new WesterosHouse("Stark", "Winter is Coming"),
new WesterosHouse("Lannister", "Hear Me Roar!"), new WesterosHouse("Greyjoy", "We Do Not Sow"),
new WesterosHouse("Baratheon", "Our is the Fury"), new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"),
new WesterosHouse("Tyrell", "Growing Strong") };
// let's verify the words of the great houses of Westeros:
assertThat(greatHousesOfWesteros).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 values is consistent with the order of the array under test.
P - the type of elements extracted.method - the name of the method which result is to be extracted from the array under testextractingType - type to returnIllegalArgumentException - if no method exists with the given name, or method is not public, or method does
return void, or method accepts arguments.public SELF inHexadecimal()
It can be useful to better understand what the error was with a more meaningful error message.
Example
assertThat(new Byte[] { 0x10, 0x20 }).inHexadecimal().contains(new Byte[] { 0x30 });
With standard error message:
Expecting:
<[16, 32]>
to contain:
<[48]>
but could not find:
<[48]>
With Hexadecimal error message:
Expecting:
<[0x10, 0x20]>
to contain:
<[0x30]>
but could not find:
<[0x30]>inHexadecimal in class AbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT[]>this assertion object.public SELF inBinary()
AbstractAssertExample:
assertThat(1).inBinary().isEqualTo(2);
org.junit.ComparisonFailure:
Expected :0b00000000_00000000_00000000_00000010
Actual :0b00000000_00000000_00000000_00000001inBinary in class AbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,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);
Employee[] employees = new Employee[] { 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 array
elements.
You can chain filters:
// fellowshipOfTheRing is an array 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(Condition) or filteredOn(Predicate) and
provide a Condition or Predicate to specify the filter to apply.
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 array elements.public SELF filteredOnNull(String propertyOrFieldName)
propertyOrFieldName are 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);
Employee[] employees = new Employee[] { 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 array
elements.propertyOrFieldName - the name of the property or field to readIntrospectionError - if the given propertyOrFieldName can't be found in one of the array 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);
Employee[] employees = new Employee[] { 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 array
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 an array 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(Condition) or filteredOn(Predicate) and
provide a Condition or Predicate to specify the filter to apply.
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,
allowing to perform assertions on the filtered list.
Let's 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);
Employee[] employees = new Employee[] { 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 SELF filteredOn(Predicate<? super ELEMENT> predicate)
Predicate,
allowing to perform assertions on the filtered list.
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[] employees = new Employee[] { yoda, luke, obiwan };
assertThat(employees).filteredOn(employee -> employee.getAge() > 100)
.containsOnly(yoda, obiwan);predicate - the filter predicateIllegalArgumentException - if the given predicate is null.public <T> SELF filteredOn(Function<? super ELEMENT,T> function, T expectedValue)
function is equal to expectedValue.
It allows to filter elements in more safe way 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);
Employee[] employees = new Employee[] { 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 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[] employees = new Employee[] { yoda, luke, obiwan };
assertThat(employees).filteredOnAssertions(employee -> assertThat(employee.getAge()).isGreaterThan(100))
.containsOnly(yoda, obiwan);elementAssertions - containing AssertJ assertions to filter onIllegalArgumentException - if the given predicate is null.public SELF filteredOnAssertions(ThrowingConsumer<? super ELEMENT> elementAssertions)
Consumer.
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[] employees = new Employee[] { yoda, luke, obiwan };
// compiles even if getAge() throws a checked exception unlike filteredOnAssertions(Consumer)
assertThat(employees).filteredOnAssertions(employee -> assertThat(employee.getAge()).isGreaterThan(100))
.containsOnly(yoda, obiwan);elementAssertions - containing AssertJ assertions to filter onIllegalArgumentException - if the given predicate is null.RuntimeException - rethrown as is by the given ThrowingConsumer or wrapping any Throwable.public SELF allMatch(Predicate<? super ELEMENT> predicate)
Predicate.
Example :
String[] abc = {"a", "b", "c"};
String[] abcc = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>predicate - the given Predicate.this object.NullPointerException - if the given predicate is null.AssertionError - if an element cannot be cast to ELEMENT.AssertionError - if one or more elements don't satisfy the given predicate.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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,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 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
FileReader[] readers = { new FileReader("ABC.txt"), new FileReader("XYZ.txt") };
// assertion succeeds as none of the files are empty
assertThat(readers).allSatisfy(isNotEmpty);
// assertion fails as XYZ.txt does not start with 'A':
assertThat(readers).allSatisfy(startsWithA);
If the actual array is empty, this assertion succeeds as there is nothing to check.
allSatisfy in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>requirements - the given ThrowingConsumer.this object.NullPointerException - if given ThrowingConsumer is nullRuntimeException - rethrown as is by the given ThrowingConsumer or wrapping any Throwable.AssertionError - if one or more elements don't satisfy the given requirements.public SELF anyMatch(Predicate<? super ELEMENT> predicate)
Predicate.
Example :
String[] abcc = { "a", "b", "cc" };
// assertion will pass
assertThat(abc).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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>predicate - the given Predicate.this object.NullPointerException - if the given predicate is null.AssertionError - if no elements satisfy the given predicate.public <OTHER_ELEMENT> SELF zipSatisfy(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:
Adress[] addressModels = findGoodRestaurants();
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 array elements.other - the array 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 array to zip actual with is null.AssertionError - if the array 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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,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 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
FileReader[] readers = { new FileReader("ABC.txt"), new FileReader("XYZ.txt") };
// assertion succeeds as ABC.txt starts with 'A'
assertThat(readers).anySatisfy(startsWithA);
// assertion fails none of the files starts with 'Z':
assertThat(readers).anySatisfy(startsWithZ);
If the actual array is empty, this assertion succeeds as there is nothing to check.
anySatisfy in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>requirements - the given ThrowingConsumer.this object.NullPointerException - if given ThrowingConsumer is nullRuntimeException - rethrown as is by the given ThrowingConsumer or wrapping any Throwable.AssertionError - no elements satisfy the given requirements.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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,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 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
FileReader[] readers = { new FileReader("ABC.txt"), new FileReader("XYZ.txt") };
// assertion succeeds as none of the file starts 'Z'
assertThat(readers).noneSatisfy(startsWithZ);
// assertion fails as ABC.txt starts with 'A':
assertThat(readers).noneSatisfy(startsWithA);
Note that this assertion succeeds if the group (collection, array, ...) is empty whatever the restrictions are.
noneSatisfy in interface ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>restrictions - the given ThrowingConsumer.this object.NullPointerException - if given ThrowingConsumer is nullRuntimeException - rethrown as is by the given ThrowingConsumer or wrapping any Throwable.AssertionError - if one or more elements satisfy the given requirements.@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:
TolkienCharacter[] characters = {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 that one assertion per requirements
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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>requirements - the requirements to meet.this to chain assertions.NullPointerException - if given requirements are null.AssertionError - if any element does not satisfy the requirements at the same indexAssertionError - if there are not as many requirements as there are iterable elements.@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 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:
TolkienCharacter[] characters = {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 that one assertion per requirements
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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>requirements - the requirements to meet.this to chain assertions.NullPointerException - if given requirements are null.RuntimeException - rethrown as is by the given ThrowingConsumer or wrapping any Throwable.AssertionError - if any element does not satisfy the requirements at the same indexAssertionError - if there are not as many requirements as there are iterable elements.protected SELF satisfiesExactlyForProxy(Consumer<? super ELEMENT>[] requirements)
@SafeVarargs public final SELF satisfiesExactlyInAnyOrder(Consumer<? super ELEMENT>... requirements)
This is a variation of satisfiesExactly(Consumer...) where order does not matter.
Examples:
String[] starWarsCharacterNames = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>requirements - the consumers that are expected to be satisfied by the elements of the given Iterable.NullPointerException - if the given consumers array or any consumer is null.AssertionError - if there is no permutation of elements that satisfies the individual consumers in orderAssertionError - if there are not as many requirements as there are iterable elements.@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 satisfiesExactly(ThrowingConsumer...) where order does not matter.
Examples:
String[] starWarsCharacterNames = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>requirements - the consumers that are expected to be satisfied by the elements of the given Iterable.NullPointerException - if the given consumers array or any consumer is null.RuntimeException - rethrown as is by the given ThrowingConsumer or wrapping any Throwable.AssertionError - if there is no permutation of elements that satisfies the individual consumers in orderAssertionError - if there are not as many requirements as there are iterable elements.protected SELF satisfiesExactlyInAnyOrderForProxy(Consumer<? super ELEMENT>[] requirements)
@SafeVarargs public final SELF containsAnyOf(ELEMENT... values)
Example :
String[] abc = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>values - the values whose at least one which is expected to be in the array under test.this assertion object.NullPointerException - if the array of values is null.IllegalArgumentException - if the array of values is empty and the array under test is not empty.AssertionError - if the array under test is null.AssertionError - if the array under test does not contain any of the given values.public SELF containsAnyElementsOf(Iterable<? extends ELEMENT> iterable)
Iterable elements.
Example :
String[] abc = {"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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>iterable - the iterable whose at least one element is expected to be in the array 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 array under test is not empty.AssertionError - if the array under test is null.AssertionError - if the array under test does not contain any of elements from the given Iterable.public SELF noneMatch(Predicate<? super ELEMENT> predicate)
Predicate.
Example :
String[] abcc = { "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<AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>,ELEMENT>predicate - the given Predicate.this object.NullPointerException - if the given predicate is null.AssertionError - if an element cannot be cast to ELEMENT.AssertionError - if any element satisfy the given predicate.protected <E> AbstractListAssert<?,List<? extends E>,E,ObjectAssert<E>> newListAssertInstance(List<? extends E> newActual)
Implementations need to redefine either to be proxy friendly (i.e. no final assertion methods)
or generic vararg friendly (to use SafeVarargs annotation which requires final method).
The default implementation will assume that this concrete implementation is NOT a soft assertion.
newListAssertInstance in class AbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT[]>E - the type of elements.newActual - new valueAbstractListAssert.public RecursiveComparisonAssert<?> usingRecursiveComparison()
RecursiveComparisonAssert,
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);
Doctor[] doctors = { drSheldon, drLeonard, drRaj };
Person[] people = { 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.
Person[] otherPeople = { howard, sheldon, raj };
assertThat(doctors).usingRecursiveComparison()
.isEqualTo(otherPeople);
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:
Person[] and a PersonDto[].withStrictTypeChecking.java.lang.Double: DoubleComparator with precision of 1.0E-15java.lang.Float: FloatComparator with precision of 1.0E-6AbstractIterableAssert.usingComparatorForType(Comparator, Class) usingRecursiveComparison in class AbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT[]>RecursiveComparisonAssert instanceRecursiveComparisonConfigurationpublic RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration)
usingRecursiveComparison() but allows to specify your own RecursiveComparisonConfiguration.usingRecursiveComparison in class AbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT[]>recursiveComparisonConfiguration - the RecursiveComparisonConfiguration used in the chained isEqualTo assertion.RecursiveComparisonAssert instance built with the given RecursiveComparisonConfiguration.public ObjectAssert<ELEMENT> singleElement()
By default available assertions after singleElement() are Object assertions, it is possible though to
get more specific assertions by using singleElement(element assert factory)
Example:
String[] babySimpsons = { "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
String[] simpsons = { "Homer", "Marge", "Lisa", "Bart", "Maggie" };
assertThat(simpsons).singleElement();AssertionError - if the actual array does not contain exactly one element.singleElement(InstanceOfAssertFactory)public <ASSERT extends AbstractAssert<?,?>> ASSERT singleElement(InstanceOfAssertFactory<?,ASSERT> assertFactory)
AssertFactory parameter.
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
String[] babySimpsons = { "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
String[] simpsons = { "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 array does not contain exactly one element.NullPointerException - if the given factory is null.protected TypeComparators getComparatorsByType()
protected TypeComparators getComparatorsForElementPropertyOrFieldTypes()
Copyright © 2025. All rights reserved.