Class AbstractObjectArrayAssert<SELF extends AbstractObjectArrayAssert<SELF,ELEMENT>,ELEMENT>
- Type Parameters:
ELEMENT
- the type of elements of the "actual" value.
- All Implemented Interfaces:
ArraySortedAssert<AbstractObjectArrayAssert<SELF,
,ELEMENT>, ELEMENT> Assert<SELF,
,ELEMENT[]> Descriptable<SELF>
,EnumerableAssert<AbstractObjectArrayAssert<SELF,
,ELEMENT>, ELEMENT> ExtensionPoints<SELF,
,ELEMENT[]> IndexedObjectEnumerableAssert<AbstractObjectArrayAssert<SELF,
,ELEMENT>, ELEMENT> ObjectEnumerableAssert<AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT>
- Direct Known Subclasses:
ObjectArrayAssert
To create an instance of this class, invoke
.
Assertions.assertThat(Object[])
-
Field Summary
FieldsModifier and TypeFieldDescription(package private) ObjectArrays
private Map<String,
Comparator<?>> private TypeComparators
(package private) Iterables
Fields inherited from class org.assertj.core.api.AbstractAssert
actual, conditions, info, myself, objects
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionVerifies that all elements match the givenPredicate
.Verifies that all the elements of actual match the givenPredicate
.allSatisfy
(Consumer<? super ELEMENT> requirements) Verifies that all the elements satisfy given requirements expressed as aConsumer
.anySatisfy
(Consumer<? super ELEMENT> requirements) Verifies that at least one element satisfies the given requirements expressed as aConsumer
.Verifies that each element value satisfies the given conditionareAtLeast
(int times, Condition<? super ELEMENT> condition) Verifies that there are at least n elements in the actual group satisfying the given condition.areAtLeastOne
(Condition<? super ELEMENT> condition) Verifies that there is at least one element in the actual array satisfying the given condition.Verifies that there are at most n elements in the actual group satisfying the given condition.areExactly
(int times, Condition<? super ELEMENT> condition) Verifies that there are exactly n elements in the actual group satisfying the given condition.Verifies that each element value does not satisfy the given conditionSets the description of the assertion that is going to be called after.as
(Description description) Sets the description of the assertion that is going to be called after.Verifies that the actual group contains the given values, in any order.Verifies that the actual array contains the given object at the given index.containsAll
(Iterable<? extends ELEMENT> iterable) Verifies that the actual array contains all the elements of givenIterable
, in any order.containsExactly
(ELEMENT... values) Verifies that the actual array contains only the given values and nothing else, in order.containsExactlyElementsOf
(Iterable<? extends ELEMENT> iterable) Same ascontainsExactly(Object...)
but handles theIterable
to array conversion : verifies that actual contains all elements of the givenIterable
and nothing else in the same order.containsExactlyInAnyOrder
(ELEMENT... values) Verifies that the actual array contains exactly the given values and nothing else, in any order.Verifies that the actual array contains at least a null element.containsOnly
(ELEMENT... values) Verifies that the actual group contains only the given values and nothing else, in any order.containsOnlyElementsOf
(Iterable<? extends ELEMENT> iterable) Same semantic ascontainsOnly(Object[])
: verifies that actual contains all elements of the givenIterable
and nothing else, in any order.containsOnlyOnce
(ELEMENT... values) Verifies that the actual group contains the given values only once.containsSequence
(ELEMENT... sequence) Verifies that the actual array contains the given sequence in the correct order and without extra values between the sequence values.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.containsSubsequence
(ELEMENT... subsequence) Verifies that the actual array contains the given subsequence in the correct order (possibly with other values between them).containsSubsequence
(Iterable<? extends ELEMENT> subsequence) Verifies that the actual array contains the given subsequence in the correct order (possibly with other values between them).doesNotContain
(ELEMENT... values) Verifies that the actual array does not contain the given values.doesNotContain
(ELEMENT value, Index index) Verifies that the actual array does not contain the given object at the given index.doesNotContainAnyElementsOf
(Iterable<? extends ELEMENT> iterable) Verifies that the actual array does not contain any elements of the givenIterable
(i.e.Verifies that the actual array does not contain null elements.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.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.doesNotContainSubsequence
(ELEMENT... subsequence) Verifies that the actual array does not contain the given subsequence in the correct order (possibly with other values between them).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).Verifies that the actual array does not contain duplicates.private <U,
C extends Collection<U>>
ObjectArrayAssert<U>doFlatExtracting
(Extractor<? super ELEMENT, C> extractor) Verifies that all elements don't satisfy the given condition.Verifies that the actual array ends with the given sequence of objects, without any other objects between them.extracting
(String fieldOrProperty) Extract the values of given field or property from the array's elements under test into a new array, this new array becoming the array under test.extracting
(String... propertiesOrFields) Extract the values of given fields/properties from the array's elements under test into a new array composed of Tuple (a simple data structure), this new array becoming the array under test.<P> ObjectArrayAssert<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 array, this new array becoming the array under test with type.final ObjectArrayAssert<Tuple>
extracting
(Function<ELEMENT, ?>... extractors) <U> ObjectArrayAssert<U>
extracting
(Extractor<? super ELEMENT, U> extractor) Extract the values from the array's elements by applying an extracting function on them.<U,
EXCEPTION extends Exception>
ObjectArrayAssert<U>extracting
(ThrowingExtractor<? super ELEMENT, U, EXCEPTION> extractor) Extract the values from the array's elements by applying an extracting function (which might throw an exception) on them.extractingResultOf
(String method) Extract the result of given method invocation from the array's elements under test into a new array, this new array becoming the array under test.<P> ObjectArrayAssert<P>
extractingResultOf
(String method, Class<P> extractingType) Extract the result of given method invocation from the array's elements under test into a new array, this new array becoming the array under test.filteredOn
(String propertyOrFieldName, Object expectedValue) Filter the array under test keeping only elements having a property or field equal toexpectedValue
, the property/field is specified bypropertyOrFieldName
parameter.filteredOn
(String propertyOrFieldName, FilterOperator<?> filterOperator) Filter the array under test keeping only elements having a property or field matching the filter expressed with theFilterOperator
, the property/field is specified bypropertyOrFieldName
parameter.filteredOn
(Predicate<? super ELEMENT> predicate) Filter the iterable under test keeping only elements matching the givenPredicate
.filteredOn
(Condition<? super ELEMENT> condition) Filter the array under test keeping only elements matching the givenCondition
.filteredOnNull
(String propertyOrFieldName) Filter the array under test keeping only elements whose property or field specified bypropertyOrFieldName
is null.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.<U,
C extends Collection<U>>
ObjectArrayAssert<U>flatExtracting
(Extractor<? 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.<U,
C extends Collection<U>, EXCEPTION extends Exception>
ObjectArrayAssert<U>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.hasAtLeastOneElementOfType
(Class<?> type) Verifies that at least one element in the actualObject
group has the specified type (matching includes subclasses of the given type).hasOnlyElementsOfType
(Class<?> type) Verifies that all the elements in the actualObject
group belong to the specified type (matching includes subclasses of the given type).hasOnlyElementsOfTypes
(Class<?>... types) Verifies that all elements of the actual group are instances of given classes or interfaces.void
hasOnlyOneElementSatisfying
(Consumer<ELEMENT> elementAssertions) Verifies that the unique element of the array satifies the given assertions expressed as aConsumer
, if it does not, only the first error is reported, useSoftAssertions
to get all the errors.hasSameElementsAs
(Iterable<? extends ELEMENT> iterable) An alias ofcontainsOnlyElementsOf(Iterable)
: verifies that actual contains all elements of the givenIterable
and nothing else, in any order.hasSameSizeAs
(Iterable<?> other) Verifies that the actual group has the same size as the givenIterable
.hasSameSizeAs
(Object other) Verifies that the actual array has the same size as the given array.hasSize
(int expected) Verifies that the number of values in the actual group is equal to the given one.Verifies that all elements satisfy the given condition.haveAtLeast
(int times, Condition<? super ELEMENT> condition) Verifies that there are at least n elements in the actual group satisfying the given condition.haveAtLeastOne
(Condition<? super ELEMENT> condition) Verifies that there is at least one element in the actual group satisfying the given condition.haveAtMost
(int times, Condition<? super ELEMENT> condition) Verifies that there are at most n elements in the actual group satisfying the given condition.haveExactly
(int times, Condition<? super ELEMENT> condition) Verifies that there are exactly n elements in the actual group satisfying the given condition.inBinary()
Use binary object representation instead of standard representation in error messages.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.Verifies that the actual group of values is not empty.void
Verifies that the actual group of values isnull
or empty.isSorted()
Verifies that the actual array is sorted in ascending order according to the natural ordering of its elements.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.isSubsetOf
(ELEMENT... values) Verifies that all elements of actual are present in the given values.isSubsetOf
(Iterable<? extends ELEMENT> values) Verifies that all elements of actual are present in the givenIterable
.startsWith
(ELEMENT... sequence) Verifies that the actual array starts with the given sequence of objects, without any other objects between them.<C> SELF
usingComparatorForElementFieldsWithNames
(Comparator<C> comparator, String... elementPropertyOrFieldNames) Allows to set a comparator to compare properties or fields of elements with the given names.<C> SELF
usingComparatorForElementFieldsWithType
(Comparator<C> comparator, Class<C> type) Allows to set a specific comparator to compare properties or fields of elements with the given type.Revert to standard comparison for incoming assertion group element checks.usingElementComparator
(Comparator<? super ELEMENT> elementComparator) Use given custom comparator instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks.usingElementComparatorIgnoringFields
(String... fields) Use field/property by field/property on all fields/properties except the given ones (including inherited fields/properties)instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks.usingElementComparatorOnFields
(String... fields) Use field/property by field/property comparison on the given fields/properties only (including inherited fields/properties)instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks.Use field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks.Use a recursive field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks.Methods inherited from class org.assertj.core.api.AbstractAssert
asList, asString, describedAs, describedAs, descriptionText, doesNotHave, doesNotHaveSameClassAs, equals, failWithMessage, getWritableAssertionInfo, has, hashCode, hasSameClassAs, hasToString, is, isEqualTo, isExactlyInstanceOf, isIn, isIn, isInstanceOf, isInstanceOfAny, isInstanceOfSatisfying, isNot, isNotEqualTo, isNotExactlyInstanceOf, isNotIn, isNotIn, isNotInstanceOf, isNotInstanceOfAny, isNotNull, isNotOfAnyClassIn, isNotSameAs, isNull, isOfAnyClassIn, isSameAs, matches, matches, overridingErrorMessage, satisfies, setCustomRepresentation, throwAssertionError, usingComparator, usingDefaultComparator, withFailMessage, withRepresentation, withThreadDumpOnError
-
Field Details
-
arrays
ObjectArrays arrays -
iterables
Iterables iterables -
comparatorsForElementPropertyOrFieldNames
-
comparatorsForElementPropertyOrFieldTypes
-
-
Constructor Details
-
AbstractObjectArrayAssert
-
-
Method Details
-
as
Description copied from class:AbstractAssert
Sets the description of the assertion that is going to be called after.You 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.- Specified by:
as
in interfaceDescriptable<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>> - Overrides:
as
in classAbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT[]> - Parameters:
description
- the new description to set.- Returns:
this
object.- See Also:
-
as
Description copied from class:AbstractAssert
Sets the description of the assertion that is going to be called after.You 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 a bad 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] expected:<[33]> but was:<[50]>"); }
- Specified by:
as
in interfaceDescriptable<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>> - Overrides:
as
in classAbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT[]> - Parameters:
description
- the new description to set.args
- optional parameter if description is a format String.- Returns:
this
object.- See Also:
-
isNullOrEmpty
public void isNullOrEmpty()Verifies that the actual group of values isnull
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();
- Specified by:
isNullOrEmpty
in interfaceEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Throws:
AssertionError
- if the actual group of values is notnull
or not empty.
-
isEmpty
public void isEmpty()Verifies that the actual group of values is empty.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();
- Specified by:
isEmpty
in interfaceEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Throws:
AssertionError
- if the actual group of values is not empty.
-
isNotEmpty
Verifies that the actual group of values is not empty.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();
- Specified by:
isNotEmpty
in interfaceEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Returns:
this
assertion object.- Throws:
AssertionError
- if the actual group of values is empty.
-
hasSize
Verifies that the number of values in the actual group is equal to the given one.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);
- Specified by:
hasSize
in interfaceEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
expected
- the expected number of values in the actual group.- Returns:
this
assertion object.- Throws:
AssertionError
- if the number of values of the actual group is not equal to the given one.
-
hasSameSizeAs
Verifies that the actual array has the same size as the given array.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);
- Specified by:
hasSameSizeAs
in interfaceEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
other
- the array to compare size with actual group.- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the array parameter isnull
or is not a true array.AssertionError
- if actual group and given array don't have the same size.
-
hasSameSizeAs
Verifies that the actual group has the same size as the givenIterable
.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"));
- Specified by:
hasSameSizeAs
in interfaceEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
other
- theIterable
to compare size with actual group.- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the otherIterable
isnull
.AssertionError
- if actual group and givenIterable
don't have the same size.
-
contains
Verifies that the actual group contains the given values, in any order.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");
- Specified by:
contains
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
values
- the given values.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.IllegalArgumentException
- if the given argument is an empty array.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group does not contain the given values.
-
containsOnly
Verifies that the actual group contains only the given values and nothing else, in any order.Example :
String[] abc = {"a", "b", "c"}; // assertions will pass assertThat(abc).containsOnly("c", "b", "a"); assertThat(abc).containsOnly("a", "a", "b", "c", "c"); // assertion will fail because "c" is missing assertThat(abc).containsOnly("a", "b");
- Specified by:
containsOnly
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
values
- the given values.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.IllegalArgumentException
- if the given argument is an empty array.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group does not contain the given values, i.e. the actual group contains some or none of the given values, or the actual group contains more values than the given ones.
-
containsOnlyElementsOf
Same semantic ascontainsOnly(Object[])
: verifies that actual contains all elements of the givenIterable
and nothing else, in any order.Example :
Ring[] rings = {nenya, vilya}; // assertions will pass assertThat(rings).containsOnlyElementsOf(newArrayList(nenya, vilya)); assertThat(rings).containsOnlyElementsOf(newArrayList(nenya, nenya, vilya, vilya)); // 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));
- Specified by:
containsOnlyElementsOf
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
iterable
- the givenIterable
we will get elements from.
-
hasOnlyOneElementSatisfying
Verifies that the unique element of the array satifies the given assertions expressed as aConsumer
, if it does not, only the first error is reported, useSoftAssertions
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"));
- Parameters:
elementAssertions
- the assertions to perform on the unique element.- Throws:
AssertionError
- if the array does not have a unique element.AssertionError
- if the array's unique element does not satifies the given assertions.- Since:
- 3.5.0
-
hasSameElementsAs
An alias ofcontainsOnlyElementsOf(Iterable)
: verifies that actual contains all elements of the givenIterable
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));
- Specified by:
hasSameElementsAs
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
iterable
- theIterable
whose elements we expect to be present- Returns:
- this assertion object
- Throws:
AssertionError
- if the actual group isnull
NullPointerException
- if the givenIterable
isnull
AssertionError
- if the actualIterable
does not have the same elements, in any order, as the givenIterable
-
containsOnlyOnce
Verifies that the actual group contains the given values only once.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");
- Specified by:
containsOnlyOnce
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
values
- the given values.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.IllegalArgumentException
- if the given argument is an empty array.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group does not contain the given values, i.e. the actual group contains some or none of the given values, or the actual group contains more than once these values.
-
containsExactly
Verifies that the actual array contains only the given values and nothing else, in order.
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);
- Specified by:
containsExactly
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
values
- the given values.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group does not contain the given values with same order, i.e. the actual group contains some or none of the given values, or the actual group contains more values than the given ones or values are the same but the order is not.
-
containsExactlyInAnyOrder
Verifies that the actual array contains exactly the given values and nothing else, in any order.
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);
- Specified by:
containsExactlyInAnyOrder
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
values
- the given values.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.AssertionError
- if the actual array isnull
.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 group contains more values than the given ones.
-
containsExactlyElementsOf
Same ascontainsExactly(Object...)
but handles theIterable
to array conversion : verifies that actual contains all elements of the givenIterable
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));
- Specified by:
containsExactlyElementsOf
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
iterable
- the givenIterable
we will get elements from.
-
containsSequence
Verifies that the actual array contains the given sequence in the correct order and without extra values between the sequence values.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);
- Specified by:
containsSequence
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
sequence
- the sequence of objects to look for.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the given array isnull
.AssertionError
- if the actual group does not contain the given sequence.
-
containsSequence
Verifies that the actual array contains the given sequence in the correct order and without extra values between the sequence values.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));
- Specified by:
containsSequence
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
sequence
- the sequence of objects to look for.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the given array isnull
.AssertionError
- if the actual group does not contain the given sequence.
-
doesNotContainSequence
Verifies that the actual array does not contain the given sequence in the given order and without extra values between the sequence values.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);
- Specified by:
doesNotContainSequence
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
sequence
- the sequence of objects to look for.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the given array isnull
.AssertionError
- if the actual group does not contain the given sequence.
-
doesNotContainSequence
Verifies that the actual array does not contain the given sequence in the given order and without extra values between the sequence values.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));
- Specified by:
doesNotContainSequence
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
sequence
- the sequence of objects to look for.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the given array isnull
.AssertionError
- if the actual group does not contain the given sequence.
-
containsSubsequence
Verifies that the actual array contains the given subsequence in the correct order (possibly with other values between them).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);
- Specified by:
containsSubsequence
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
subsequence
- the subsequence of objects to look for.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the given array isnull
.AssertionError
- if the actual group does not contain the given subsequence.
-
containsSubsequence
Verifies that the actual array contains the given subsequence in the correct order (possibly with other values between them).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));
- Specified by:
containsSubsequence
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
subsequence
- the subsequence of objects to look for.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the given array isnull
.AssertionError
- if the actual group does not contain the given subsequence.
-
doesNotContainSubsequence
Verifies that the actual array does not contain the given subsequence in the correct order (possibly with other values between them).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);
- Specified by:
doesNotContainSubsequence
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
subsequence
- the subsequence of objects to look for.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the given array isnull
.AssertionError
- if the actual group contains the given subsequence.
-
doesNotContainSubsequence
Verifies that the actual array does not contain the given subsequence in the correct order (possibly with other values between them).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));
- Specified by:
doesNotContainSubsequence
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
subsequence
- the subsequence of objects to look for.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the given array isnull
.AssertionError
- if the actual group contains the given subsequence.
-
contains
Verifies that the actual array contains the given object at the given 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));
- Specified by:
contains
in interfaceIndexedObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
value
- the object to look for.index
- the index where the object should be stored in the actual group.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
or empty.NullPointerException
- if the givenIndex
isnull
.IndexOutOfBoundsException
- if the value of the givenIndex
is equal to or greater than the size of the actual group.AssertionError
- if the actual group does not contain the given object at the given index.
-
hasOnlyElementsOfTypes
Verifies that all elements of the actual group are instances of given classes or interfaces.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);
- Specified by:
hasOnlyElementsOfTypes
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
types
- the expected classes and interfaces- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.AssertionError
- if the actual group isnull
.AssertionError
- if not all elements of the actual group are instances of one of the given types- Since:
- 2.7.0 / 3.7.0
-
doesNotContain
Verifies that the actual array does not contain the given object at the given 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));
- Specified by:
doesNotContain
in interfaceIndexedObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
value
- the object to look for.index
- the index where the object should not be stored in the actual group.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actual group isnull
.NullPointerException
- if the givenIndex
isnull
.AssertionError
- if the actual group contains the given object at the given index.
-
doesNotContain
Verifies that the actual array does not contain the given 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");
- Specified by:
doesNotContain
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
values
- the given values.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.IllegalArgumentException
- if the given argument is an empty array.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group contains any of the given values.
-
doesNotContainAnyElementsOf
Verifies that the actual array does not contain any elements of the givenIterable
(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"));
- Specified by:
doesNotContainAnyElementsOf
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
iterable
- theIterable
whose elements must not be in the actual group.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.IllegalArgumentException
- if the given argument is an empty iterable.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group contains some elements of the givenIterable
.
-
doesNotHaveDuplicates
Verifies that the actual array does not contain duplicates.Example :
String[] abc = {"a", "b", "c"}; String[] lotsOfAs = {"a", "a", "a"}; // assertion will pass assertThat(abc).doesNotHaveDuplicates(); // assertion will fail assertThat(lotsOfAs).doesNotHaveDuplicates();
- Specified by:
doesNotHaveDuplicates
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Returns:
this
assertion object.- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the actual group contains duplicates.
-
startsWith
Verifies that the actual array starts with the given sequence of objects, without any other objects between them. Similar to
, but it also verifies that the first element in the sequence is also the first element of the actual array.containsSequence(Object...)
Example :
String[] abc = {"a", "b", "c"}; // assertion will pass assertThat(abc).startsWith("a", "b"); // assertion will fail assertThat(abc).startsWith("c");
- Specified by:
startsWith
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
sequence
- the sequence of objects to look for.- Returns:
- this assertion object.
- Throws:
NullPointerException
- if the given argument isnull
.IllegalArgumentException
- if the given argument is an empty array.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group does not start with the given sequence of objects.
-
endsWith
Verifies that the actual array ends with the given sequence of objects, without any other objects between them. Similar to
, but it also verifies that the last element in the sequence is also last element of the actual array.containsSequence(Object...)
Example :
String[] abc = {"a", "b", "c"}; // assertion will pass assertThat(abc).endsWith("b", "c"); // assertion will fail assertThat(abc).endsWith("a");
- Specified by:
endsWith
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
sequence
- the sequence of objects to look for.- Returns:
- this assertion object.
- Throws:
NullPointerException
- if the given argument isnull
.IllegalArgumentException
- if the given argument is an empty array.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group does not end with the given sequence of objects.
-
isSubsetOf
Verifies that all elements of actual are present in the givenIterable
.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));
- Specified by:
isSubsetOf
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
values
- theIterable
that should contain all actual elements.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actualIterable
isnull
.NullPointerException
- if the givenIterable
isnull
.AssertionError
- if the actualIterable
is not subset of setIterable
.
-
isSubsetOf
Verifies that all elements of actual are present in the given 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);
- Specified by:
isSubsetOf
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
values
- the values that should be used for checking the elements of actual.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actualIterable
isnull
.AssertionError
- if the actualIterable
is not subset of the given values.
-
containsNull
Verifies that the actual array contains at least a null element.Example :
String[] abc = {"a", "b", "c"}; String[] abNull = {"a", "b", null}; // assertion will pass assertThat(abNull).containsNull(); // assertion will fail assertThat(abc).containsNull();
- Specified by:
containsNull
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Returns:
this
assertion object.- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the actual group does not contain a null element.
-
doesNotContainNull
Verifies that the actual array does not contain null elements.Example :
String[] abc = {"a", "b", "c"}; String[] abNull = {"a", "b", null}; // assertion will pass assertThat(abc).doesNotContainNull(); // assertion will fail assertThat(abNull).doesNotContainNull();
- Specified by:
doesNotContainNull
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Returns:
this
assertion object.- Throws:
AssertionError
- if the actual group isnull
.AssertionError
- if the actual group contains a null element.
-
are
Verifies that each element value satisfies the given conditionExample :
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);
- Specified by:
are
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
condition
- the given condition.- Returns:
this
object.- Throws:
NullPointerException
- if the given condition isnull
.AssertionError
- if an element cannot be cast to T.AssertionError
- if one or more elements don't satisfy the given condition.
-
areNot
Verifies that each element value does not satisfy the given conditionExample :
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);
- Specified by:
areNot
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
condition
- the given condition.- Returns:
this
object.- Throws:
NullPointerException
- if the given condition isnull
.AssertionError
- if an element cannot be cast to T.AssertionError
- if one or more elements satisfy the given condition.
-
have
Verifies that all elements satisfy the given 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);
- Specified by:
have
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
condition
- the given condition.- Returns:
this
object.- Throws:
NullPointerException
- if the given condition isnull
.AssertionError
- if an element cannot be cast to T.AssertionError
- if one or more elements do not satisfy the given condition.
-
doNotHave
Verifies that all elements don't satisfy the given 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);
- Specified by:
doNotHave
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
condition
- the given condition.- Returns:
this
object.- Throws:
NullPointerException
- if the given condition isnull
.AssertionError
- if an element cannot be cast to T.AssertionError
- if one or more elements satisfy the given condition.
-
areAtLeast
Verifies that there are at least n elements in the actual group satisfying the given 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);
- Specified by:
areAtLeast
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
times
- the minimum number of times the condition should be verified.condition
- the given condition.- Returns:
this
object.- Throws:
NullPointerException
- if the given condition isnull
.AssertionError
- if an element can not be cast to T.AssertionError
- if the number of elements satisfying the given condition is < n.
-
areAtLeastOne
Verifies that there is at least one element in the actual array satisfying the given condition.This method is an alias for
areAtLeast(1, condition)
.Example:
// jedi is a Condition<String> assertThat(new String[]{"Luke", "Solo", "Leia"}).areAtLeastOne(jedi);
- Specified by:
areAtLeastOne
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - See Also:
-
areAtMost
Verifies that there are at most n elements in the actual group satisfying the given 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);
- Specified by:
areAtMost
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
times
- the number of times the condition should be at most verified.condition
- the given condition.- Returns:
this
object.- Throws:
NullPointerException
- if the given condition isnull
.AssertionError
- if an element cannot be cast to T.AssertionError
- if the number of elements satisfying the given condition is > n.
-
areExactly
Verifies that there are exactly n elements in the actual group satisfying the given 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);
- Specified by:
areExactly
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
times
- the exact number of times the condition should be verified.condition
- the given condition.- Returns:
this
object.- Throws:
NullPointerException
- if the given condition isnull
.AssertionError
- if an element cannot be cast to T.AssertionError
- if the number of elements satisfying the given condition is ≠ n.
-
haveAtLeastOne
Verifies that there is at least one element in the actual group satisfying the given condition.This method is an alias for
haveAtLeast(1, condition)
.Example:
BasketBallPlayer[] bullsPlayers = {butler, rose}; // potentialMvp is a Condition<BasketBallPlayer> assertThat(bullsPlayers).haveAtLeastOne(potentialMvp);
- Specified by:
haveAtLeastOne
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - See Also:
-
haveAtLeast
Verifies that there are at least n elements in the actual group satisfying the given condition.Example :
This method is an alias forint[] 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);
areAtLeast(int, Condition)
.- Specified by:
haveAtLeast
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT>
-
haveAtMost
Verifies that there are at most n elements in the actual group satisfying the given condition.Example :
This method is an aliasint[] 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);
areAtMost(int, Condition)
.- Specified by:
haveAtMost
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT>
-
haveExactly
Verifies that there are exactly n elements in the actual group satisfying the given condition.Example :
This method is an aliasint[] 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);
areExactly(int, Condition)
.- Specified by:
haveExactly
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT>
-
hasAtLeastOneElementOfType
Verifies that at least one element in the actualObject
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);
- Specified by:
hasAtLeastOneElementOfType
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
type
- the expected type.- Returns:
- this assertion object.
-
hasOnlyElementsOfType
Verifies that all the elements in the actualObject
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);
- Specified by:
hasOnlyElementsOfType
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
type
- the expected type.- Returns:
- this assertion object.
-
isSorted
Verifies that the actual array is sorted in ascending order according to the natural ordering of its elements.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 :- a array composed of {2, 4, 6} is ok because the element type is a primitive type.
- a array composed of {"a1", "a2", "a3"} is ok because the element type (String) is Comparable
- a array composed of Rectangle {r1, r2, r3} is NOT ok because Rectangle is not Comparable
- a array composed of {True, "abc", False} is NOT ok because elements are not mutually comparable (even though each element type implements Comparable)
- Specified by:
isSorted
in interfaceArraySortedAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Returns:
this
assertion object.
-
isSortedAccordingTo
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.- Specified by:
isSortedAccordingTo
in interfaceArraySortedAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
comparator
- theComparator
used to compare array elements- Returns:
this
assertion object.
-
containsAll
Verifies that the actual array contains all the elements of givenIterable
, 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"));
- Specified by:
containsAll
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
iterable
- the givenIterable
we will get elements from.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given argument isnull
.AssertionError
- if the actual group isnull
.AssertionError
- if the actual group does not contain all the elements of givenIterable
.
-
usingElementComparator
Use given custom comparator instead of relying on actual type Aequals
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);
- Specified by:
usingElementComparator
in interfaceEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
elementComparator
- the comparator to use for incoming assertion checks.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given comparator isnull
.
-
usingDefaultElementComparator
Revert to standard comparison for incoming assertion group element checks.This method should be used to disable a custom comparison strategy set by calling
EnumerableAssert.usingElementComparator(Comparator)
.- Specified by:
usingDefaultElementComparator
in interfaceEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Returns:
this
assertion object.
-
usingComparatorForElementFieldsWithNames
public <C> SELF usingComparatorForElementFieldsWithNames(Comparator<C> comparator, String... elementPropertyOrFieldNames) 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);
- Parameters:
comparator
- theComparator
to useelementPropertyOrFieldNames
- the names of the properties and/or fields of the elements the comparator should be used for- Returns:
this
assertions object- Since:
- 2.5.0 / 3.5.0
-
usingComparatorForElementFieldsWithType
Allows to set a specific comparator to compare properties or fields of elements with the given type. A typical usage is for comparing fields of numeric type at a given precision.To be used, comparators need to be specified by this method before calling any of:
usingFieldByFieldElementComparator()
usingElementComparatorOnFields(java.lang.String...)
usingElementComparatorIgnoringFields(java.lang.String...)
usingRecursiveFieldByFieldElementComparator()
Comparators specified by
usingComparatorForElementFieldsWithNames
have precedence over comparators specified by this method.Example:
If multiple compatible comparators have been registered for a givenpublic 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);
type
, the closest in the inheritance chain to the giventype
is chosen in the following order:- The comparator for the exact given
type
- The comparator of a superclass of the given
type
- The comparator of an interface implemented by the given
type
- Parameters:
comparator
- theComparator
to usetype
- theClass
of the type of the element fields the comparator should be used for- Returns:
this
assertions object- Since:
- 2.5.0 / 3.5.0
-
usingFieldByFieldElementComparator
Use field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks. Private fields are included but this can be disabled usingAssertions.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...)
andusingComparatorForElementFieldsWithType(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
Example:equals
method.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);
- Returns:
this
assertion object.
-
usingRecursiveFieldByFieldElementComparator
Use a recursive field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks. This can be useful if actual'sequals
implementation does not suit you.The recursive property/field comparison is not applied on fields having a custom
equals
implementation, i.e. the overriddenequals
method will be used instead of a field/property by field/property comparison.You can specify a custom comparator per (nested) name or type of element field with
usingComparatorForElementFieldsWithNames
andusingComparatorForElementFieldsWithType
.The recursive comparison handles cycles.
The objects to compare can be of different types but must have the same properties/fields. For example if actual object has a
name
String field, the other object must also have one.If an object has a field and a property with the same name, the property value will be used over the field.
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT); frodo.setFriend(pippin); pippin.setFriend(frodo); TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT); frodoClone.setFriend(pippinClone); pippinClone.setFriend(frodoClone); TolkienCharacter[] hobbits = new TolkienCharacter[] {frodo, pippin}; // fails if equals has not been overridden in TolkienCharacter as it would compares object references assertThat(hobbits).contains(frodoClone, pippinClone); // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison assertThat(hobbits).usingRecursiveFieldByFieldElementComparator() .contains(frodoClone, pippinClone);
- Returns:
this
assertion object.- Since:
- 2.5.0 / 3.5.0
-
usingElementComparatorOnFields
Use field/property by field/property comparison on the given fields/properties only (including inherited fields/properties)instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks. Private fields are included but this can be disabled usingAssertions.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...)
andusingComparatorForElementFieldsWithType(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
Example:equals
method.TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT); // frodo and sam both are hobbits, so they are equals when comparing only race assertThat(array(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK // ... but not when comparing both name and race assertThat(array(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAIL
- Returns:
this
assertion object.
-
usingElementComparatorIgnoringFields
Use field/property by field/property on all fields/properties except the given ones (including inherited fields/properties)instead of relying on actual type Aequals
method to compare group elements for incoming assertion checks. Private fields are included but this can be disabled usingAssertions.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...)
andusingComparatorForElementFieldsWithType(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
Example:equals
method.TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT); // frodo and sam both are hobbits, so they are equals when comparing only race (i.e. ignoring all other fields) assertThat(array(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK // ... but not when comparing both name and race assertThat(array(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAIL
- Returns:
this
assertion object.
-
extracting
Extract the values of given field or property from the array's elements under test into a new array, this new array becoming the array under test.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 :
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.// 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");
Note that the order of extracted field/property values is consistent with the array order.
- Parameters:
fieldOrProperty
- the field/property to extract from the array under test- Returns:
- a new assertion object whose object under test is the array of extracted field/property values.
- Throws:
IntrospectionError
- if no field or property exists with the given name
-
extracting
Extract the values of given field or property from the array's elements under test into a new array, this new array becoming the array under test with type.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 :
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.// 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");
Note that the order of extracted field/property values is consistent with the order of the array under test.
- Parameters:
fieldOrProperty
- the field/property to extract from the array under testextractingType
- type to return- Returns:
- a new assertion object whose object under test is the array of extracted field/property values.
- Throws:
IntrospectionError
- if no field or property exists with the given name
-
extracting
Extract the values of given fields/properties from the array's elements under test into a new array composed of Tuple (a simple data structure), this new array becoming the array under test.It allows you to test fields/properties of the 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 :
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.// 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"));
Note that the order of extracted property/field values is consistent with the iteration order of the array under test.
- Parameters:
propertiesOrFields
- the properties/fields to extract from the initial array under test- Returns:
- a new assertion object whose object under test is the list of Tuple with extracted properties/fields values as data.
- Throws:
IntrospectionError
- if one of the given name does not match a field or property in one of the initial Iterable's element.
-
extracting
Extract the values from the array's elements by applying an extracting function on them. The returned array becomes a new object under test.It allows to test values from the elements in safer way than by using
extracting(String)
, as it doesn't utilize introspection.Let's take a look an example:
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// 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);
HashSet
, you won't be able to make any assumptions on the extracted values order.- Parameters:
extractor
- the object transforming input object to desired one- Returns:
- a new assertion object whose object under test is the list of values extracted
-
extracting
public <U,EXCEPTION extends Exception> ObjectArrayAssert<U> extracting(ThrowingExtractor<? super ELEMENT, U, EXCEPTION> extractor) Extract the values from the array's elements by applying an extracting function (which might throw an exception) on them. The returned array becomes a new object under test.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 utilize introspection.Let's take a look an example:
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// 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");
HashSet
, you won't be able to make any assumptions on the extracted values order.- Parameters:
extractor
- the object transforming input object to desired one- Returns:
- a new assertion object whose object under test is the list of values extracted
- Since:
- 3.7.0
-
extracting
Use the givenFunction
s to extract the values from the array's elements into a new array composed ofTuple
s (a simple data structure containing the extracted values), this new array 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 eachTuple
'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 :
You can use lambda expression or a method reference to extract the expected values.// 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));
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.- Parameters:
extractors
- the extractor functions to extract a value from an element of the array under test.- Returns:
- a new assertion object whose object under test is the array of Tuples containing the extracted values.
-
flatExtracting
public <U,C extends Collection<U>> ObjectArrayAssert<U> flatExtracting(Extractor<? 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.It allows testing the results of extracting values that are represented by Iterables.
For example:
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted collections.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);
- Parameters:
extractor
- the object transforming input object to an Iterable of desired ones- Returns:
- a new assertion object whose object under test is the list of values extracted
-
flatExtracting
public <U,C extends Collection<U>, ObjectArrayAssert<U> flatExtractingEXCEPTION extends Exception> (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.It allows testing the results of extracting values that are represented by Iterables.
For example:
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted collections.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);
- Parameters:
extractor
- the object transforming input object to an Iterable of desired ones- Returns:
- a new assertion object whose object under test is the list of values extracted
- Since:
- 3.7.0
-
doFlatExtracting
private <U,C extends Collection<U>> ObjectArrayAssert<U> doFlatExtracting(Extractor<? super ELEMENT, C> extractor) -
flatExtracting
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.It allows testing the elements of extracting values that are represented by iterables or arrays.
For example:
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted collections.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);
- Parameters:
propertyName
- the object transforming input object to an Iterable of desired ones- Returns:
- a new assertion object whose object under test is the list of values extracted
- Throws:
IllegalArgumentException
- if one of the extracted property value was not an array or an iterable.
-
extractingResultOf
Extract the result of given method invocation from the array's elements under test into a new array, this new array becoming the array under test.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:
- method has to be public,
- method cannot accept any arguments,
- method cannot return void.
Note that the order of extracted values is consistent with the order of the array under test.
- Parameters:
method
- the name of the method which result is to be extracted from the array under test- Returns:
- a new assertion object whose object under test is the array of extracted values.
- Throws:
IllegalArgumentException
- if no method exists with the given name, or method is not public, or method does return void, or method accepts arguments.
-
extractingResultOf
Extract the result of given method invocation from the array's elements under test into a new array, this new array becoming the array under test.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:
- method has to be public,
- method can not accept any arguments,
- method can not return void.
Note that the order of extracted values is consistent with the order of the array under test.
- Parameters:
method
- the name of the method which result is to be extracted from the array under testextractingType
- type to return- Returns:
- a new assertion object whose object under test is the array of extracted values.
- Throws:
IllegalArgumentException
- if no method exists with the given name, or method is not public, or method does return void, or method accepts arguments.
-
inHexadecimal
Enable hexadecimal object representation of Iterable elements instead of standard java representation in error messages.It can be useful to better understand what the error was with a more meaningful error message.
Example
With standard error message:assertThat(new Byte[] { 0x10, 0x20 }).inHexadecimal().contains(new Byte[] { 0x30 });
With Hexadecimal error message:Expecting: <[16, 32]> to contain: <[48]> but could not find: <[48]>
Expecting: <[0x10, 0x20]> to contain: <[0x30]> but could not find: <[0x30]>
- Overrides:
inHexadecimal
in classAbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT[]> - Returns:
this
assertion object.
-
inBinary
Description copied from class:AbstractAssert
Use binary object representation instead of standard representation in error messages.Example:
assertThat(1).inBinary().isEqualTo(2); org.junit.ComparisonFailure: Expected :0b00000000_00000000_00000000_00000010 Actual :0b00000000_00000000_00000000_00000001
- Overrides:
inBinary
in classAbstractAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT[]> - Returns:
this
assertion object.
-
filteredOn
Filter the array under test keeping only elements having a property or field equal toexpectedValue
, the property/field is specified bypropertyOrFieldName
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 callingAssertions.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):
Nested properties/fields are supported: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);
// 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 tofilteredOn(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:
If you need more complex filter, use// 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);
filteredOn(Condition)
and provide aCondition
to specify the filter to apply.- Parameters:
propertyOrFieldName
- the name of the property or field to readexpectedValue
- the value to compare element's property or field with- Returns:
- a new assertion object with the filtered array under test
- Throws:
IllegalArgumentException
- if the given propertyOrFieldName isnull
or empty.IntrospectionError
- if the given propertyOrFieldName can't be found in one of the array elements.
-
filteredOnNull
Filter the array under test keeping only elements whose property or field specified bypropertyOrFieldName
is null.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):
Nested properties/fields are supported: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);
An// Name is bean class with 'first' and 'last' String properties assertThat(employees).filteredOnNull("name.last") .containsOnly(yoda, obiwan, noname);
IntrospectionError
is thrown if the given propertyOrFieldName can't be found in one of the array elements.If you need more complex filter, use
filteredOn(Condition)
and provide aCondition
to specify the filter to apply.- Parameters:
propertyOrFieldName
- the name of the property or field to read- Returns:
- a new assertion object with the filtered array under test
- Throws:
IntrospectionError
- if the given propertyOrFieldName can't be found in one of the array elements.
-
filteredOn
Filter the array under test keeping only elements having a property or field matching the filter expressed with theFilterOperator
, the property/field is specified bypropertyOrFieldName
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 callingAssertions.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 :
AnEmployee 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);
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:
If you need more complex filter, use// 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);
filteredOn(Condition)
and provide aCondition
to specify the filter to apply.- Parameters:
propertyOrFieldName
- the name of the property or field to readfilterOperator
- the filter operator to apply- Returns:
- a new assertion object with the filtered array under test
- Throws:
IllegalArgumentException
- if the given propertyOrFieldName isnull
or empty.
-
filteredOn
Filter the array under test keeping only elements matching the givenCondition
.Let's check old employees whose age > 100:
You can combineEmployee 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);
Condition
with condition operator likeNot
:// 'not' filter is statically imported from Assertions.not assertThat(employees).filteredOn(not(oldEmployees)) .contains(luke, noname);
- Parameters:
condition
- the filter condition / predicate- Returns:
- a new assertion object with the filtered array under test
- Throws:
IllegalArgumentException
- if the given condition isnull
.
-
filteredOn
Filter the iterable under test keeping only elements matching the givenPredicate
.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);
- Parameters:
predicate
- the filter predicate- Returns:
- a new assertion object with the filtered array under test
- Throws:
IllegalArgumentException
- if the given predicate isnull
.
-
allMatch
Verifies that all elements match the givenPredicate
.Example :
Note that you can achieve the same result withString[] abc = new String[] {"a", "b", "c"}; String[] abcc = new String[] {"a", "b", "cc"}; // assertion will pass assertThat(abc).allMatch(s -> s.length() == 1); // assertion will fail assertThat(abcc).allMatch(s -> s.length() == 1);
are(Condition)
orhave(Condition)
.- Specified by:
allMatch
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
predicate
- the givenPredicate
.- Returns:
this
object.- Throws:
NullPointerException
- if the given predicate isnull
.AssertionError
- if an element cannot be cast to T.AssertionError
- if one or more elements don't satisfy the given predicate.
-
allMatch
Verifies that all the elements of actual match the givenPredicate
. The predicate description is used to get an informative error message.Example :
The message of the failed assertion would be: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");
Expecting all elements of: <["a", "b", "cc"]> to match 'length of 1' predicate but this element did not: <"cc">
- Specified by:
allMatch
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
predicate
- the givenPredicate
.predicateDescription
- a description of thePredicate
used in the error message- Returns:
this
object.
-
allSatisfy
Verifies that all the elements satisfy given requirements expressed as aConsumer
.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"); });
- Specified by:
allSatisfy
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
requirements
- the givenConsumer
.- Returns:
this
object.
-
anySatisfy
Verifies that at least one element satisfies the given requirements expressed as aConsumer
.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());
- Specified by:
anySatisfy
in interfaceObjectEnumerableAssert<SELF extends AbstractObjectArrayAssert<SELF,
ELEMENT>, ELEMENT> - Parameters:
requirements
- the givenConsumer
.- Returns:
this
object.
-