S
- the "self" type of this assertion class. Please read "Emulating 'self types' using Java Generics to simplify fluent API implementation"
for more details.A
- the type of the "actual" value.T
- the type of elements of the "actual" value.public abstract class AbstractIterableAssert<S extends AbstractIterableAssert<S,A,T>,A extends Iterable<? extends T>,T> extends AbstractAssert<S,A> implements ObjectEnumerableAssert<S,T>
ObjectEnumerableAssert
whose actual value type is
Collection
.actual, info, myself
Modifier | Constructor and Description |
---|---|
protected |
AbstractIterableAssert(A actual,
Class<?> selfType) |
Modifier and Type | Method and Description |
---|---|
S |
are(Condition<? super T> condition)
Verifies that each element value satisfies the given condition
|
S |
areAtLeast(int times,
Condition<? super T> condition)
Verifies that there is at least n elements in the actual group satisfying the given condition.
|
S |
areAtLeastOne(Condition<? super T> condition)
Verifies that there is at least one element in the actual group satisfying the given condition.
|
S |
areAtMost(int times,
Condition<? super T> condition)
Verifies that there is at most n elements in the actual group satisfying the given condition.
|
S |
areExactly(int times,
Condition<? super T> condition)
Verifies that there is exactly n elements in the actual group satisfying the given condition.
|
S |
areNot(Condition<? super T> condition)
Verifies that each element value does not satisfy the given condition
|
S |
contains(T... values)
Verifies that the actual group contains the given values, in any order.
|
S |
containsAll(Iterable<? extends T> iterable)
Verifies that the actual group contains all the elements of given
Iterable , in any order. |
S |
containsExactly(T... values)
Verifies that the actual group contains only the given values and nothing else, in order.
This assertion should only be used with group that have a consistent iteration order (i.e. |
S |
containsExactlyElementsOf(Iterable<? extends T> iterable)
Same as
containsExactly(Object[]) but handle the Iterable to array conversion. |
S |
containsNull()
Verifies that the actual group contains at least a null element.
|
S |
containsOnly(T... values)
Verifies that the actual group contains only the given values and nothing else, in any order.
|
S |
containsOnlyElementsOf(Iterable<? extends T> iterable)
Same semantic as
ObjectEnumerableAssert.containsOnly(Object[]) : verifies that actual contains all the elements of the given
iterable and nothing else, in any order. |
S |
containsOnlyOnce(T... values)
Verifies that the actual group contains the given values only once.
|
S |
containsSequence(T... sequence)
Verifies that the actual group contains the given sequence, without any other values between them.
|
S |
containsSubsequence(T... sequence)
Verifies that the actual group contains the given subsequence (possibly with other values between them).
|
S |
doesNotContain(T... values)
Verifies that the actual group does not contain the given values.
|
S |
doesNotContainAnyElementsOf(Iterable<? extends T> iterable)
Verifies that actual does not contain any elements of the given
Iterable (i.e. |
S |
doesNotContainNull()
Verifies that the actual group does not contain null elements.
|
S |
doesNotHaveDuplicates()
Verifies that the actual group does not contain duplicates.
|
S |
doNotHave(Condition<? super T> condition)
Verifies that all elements don't satisfy the given condition.
|
S |
endsWith(T... sequence)
Verifies that the actual group ends with the given sequence of objects, without any other objects between them.
|
<V> ListAssert<V> |
extracting(Extractor<? super T,V> extractor)
Extract the values from Iterable's elements under test by applying an extracting function on them.
|
ListAssert<Tuple> |
extracting(java.util.function.Function<T,?>... extractors)
|
ListAssert<Tuple> |
extracting(String... propertiesOrFields)
Extract the values of given fields/properties from the Iterable's elements under test into a new Iterable composed
of Tuple (a simple data structure), this new Iterable becoming the Iterable under test.
|
ListAssert<Object> |
extracting(String propertyOrField)
Extract the values of given field or property from the Iterable's elements under test into a new Iterable, this new
Iterable becoming the Iterable under test.
|
<P> ListAssert<P> |
extracting(String propertyOrField,
Class<P> extractingType)
Extract the values of given field or property from the Iterable's elements under test into a new Iterable, this new
Iterable becoming the Iterable under test.
|
ListAssert<Object> |
extractingResultOf(String method)
Extract the result of given method invocation on the Iterable's elements under test into a new Iterable, this new
Iterable becoming the Iterable under test.
|
<P> ListAssert<P> |
extractingResultOf(String method,
Class<P> extractedType)
Extract the result of given method invocation on the Iterable's elements under test into a new list of the given
class, this new List becoming the object under test.
|
S |
filteredOn(Condition<? super T> condition)
Filter the iterable under test keeping only elements matching the given
Condition . |
S |
filteredOn(java.util.function.Predicate<? super T> predicate)
Filter the iterable under test keeping only elements matching the given
Predicate . |
S |
filteredOn(String propertyOrFieldName,
FilterOperator<?> filterOperator)
Filter the iterable under test keeping only elements having a property or field matching the filter expressed with
the
FilterOperator , the property/field is specified by propertyOrFieldName parameter. |
S |
filteredOn(String propertyOrFieldName,
Object expectedValue)
Filter the iterable under test keeping only elements having a property or field equal to
expectedValue , the
property/field is specified by propertyOrFieldName parameter. |
S |
filteredOnNull(String propertyOrFieldName)
Filter the iterable under test keeping only elements whose property or field specified by
propertyOrFieldName is null. |
<V> ListAssert<V> |
flatExtracting(Extractor<? super T,? extends Collection<V>> extractor)
Extract the Iterable values from Iterable's elements under test by applying an Iterable extracting function on them
and concatenating the result lists.
|
ListAssert<Object> |
flatExtracting(String propertyName)
Extract from Iterable's elements the Iterable/Array values corresponding to the given property/field name and
concatenate them into a single list becoming the new object under test.
|
S |
hasAtLeastOneElementOfType(Class<?> expectedType)
Verifies that at least one element in the actual
Iterable belong to the specified type (matching includes
subclasses of the given type). |
S |
hasOnlyElementsOfType(Class<?> expectedType)
Verifies that all the elements in the actual
Iterable belong to the specified type (matching includes
subclasses of the given type). |
S |
hasSameElementsAs(Iterable<? extends T> iterable)
An alias of
ObjectEnumerableAssert.containsOnlyElementsOf(Iterable) : verifies that actual contains all the elements of the
given iterable and nothing else, in any order. |
S |
hasSameSizeAs(Iterable<?> other)
Verifies that the actual group has the same size as given
Iterable . |
S |
hasSameSizeAs(Object other)
Verifies that the actual group has the same size as given array.
|
S |
hasSize(int expected)
Verifies that the number of values in the actual group is equal to the given one.
|
S |
have(Condition<? super T> condition)
Verifies that all elements satisfy the given condition.
|
S |
haveAtLeast(int times,
Condition<? super T> condition)
Verifies that there is at least n elements in the actual group satisfying the given condition.
|
S |
haveAtLeastOne(Condition<? super T> condition)
Verifies that there is at least one element in the actual group satisfying the given condition.
|
S |
haveAtMost(int times,
Condition<? super T> condition)
Verifies that there is at most n elements in the actual group satisfying the given condition.
|
S |
haveExactly(int times,
Condition<? super T> condition)
Verifies that there is exactly n elements in the actual group satisfying the given condition.
|
S |
inBinary()
Enable binary representation of Iterable elements instead of standard representation in error messages.
|
S |
inHexadecimal()
Enable hexadecimal representation of Iterable elements instead of standard representation in error messages.
|
void |
isEmpty()
Verifies that the actual group of values is empty.
|
S |
isNotEmpty()
Verifies that the actual group of values is not empty.
|
void |
isNullOrEmpty()
Verifies that the actual group of values is
null or empty. |
S |
isSubsetOf(Iterable<? extends T> values)
Verifies that all the elements of actual are present in the given
Iterable . |
S |
startsWith(T... sequence)
Verifies that the actual group starts with the given sequence of objects, without any other objects between them.
|
protected S |
usingComparisonStrategy(ComparisonStrategy comparisonStrategy) |
S |
usingDefaultElementComparator()
Revert to standard comparison for incoming assertion group element checks.
|
S |
usingElementComparator(Comparator<? super T> elementComparator)
Use given custom comparator instead of relying on actual type A
equals method to compare group
elements for
incoming assertion checks. |
S |
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 A
equals method to compare group elements for
incoming assertion checks. |
S |
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 A
equals method to compare group elements for
incoming assertion checks. |
S |
usingFieldByFieldElementComparator()
Use field/property by field/property comparison (including inherited fields/properties) instead of relying on
actual type A
equals method to compare group elements for incoming assertion checks. |
as, as, asList, asString, describedAs, describedAs, descriptionText, doesNotHave, doesNotHaveSameClassAs, equals, failWithMessage, getWritableAssertionInfo, has, hashCode, hasSameClassAs, hasToString, is, isEqualTo, isExactlyInstanceOf, isIn, isIn, isInstanceOf, isInstanceOfAny, isNot, isNotEqualTo, isNotExactlyInstanceOf, isNotIn, isNotIn, isNotInstanceOf, isNotInstanceOfAny, isNotNull, isNotOfAnyClassIn, isNotSameAs, isNull, isOfAnyClassIn, isSameAs, matches, matches, overridingErrorMessage, throwAssertionError, usingComparator, usingDefaultComparator, withFailMessage, withThreadDumpOnError
public void isNullOrEmpty()
null
or empty.isNullOrEmpty
in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
public void isEmpty()
isEmpty
in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
public S isNotEmpty()
isNotEmpty
in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
this
assertion object.public S hasSize(int expected)
hasSize
in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
expected
- the expected number of values in the actual group.this
assertion object.public S hasSameSizeAs(Object other)
int[] oneTwoThree = {1, 2, 3};
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).hasSameSizeAs(oneTwoThree);
hasSameSizeAs
in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
other
- the array to compare size with actual group.this
assertion object.public S hasSameSizeAs(Iterable<?> other)
Iterable
.
Example:
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).hasSameSizeAs(abc);
hasSameSizeAs
in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
other
- the Iterable
to compare size with actual group.this
assertion object.public S contains(T... values)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertions will pass
assertThat(abc).contains("b", "a");
assertThat(abc).contains("b", "a", "b");
// assertions will fail
assertThat(abc).contains("d");
contains
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
values
- the given values.this
assertion object.public S containsOnly(T... values)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertion will pass
assertThat(abc).containsOnly("c", "b", "a");
// assertion will fail as some elements of abc are missing
assertThat(abc).containsOnly("a", "b");
containsOnly
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
values
- the given values.this
assertion object.public S containsOnlyOnce(T... values)
Examples :
// lists are used in the examples but it would also work with arrays
// assertions will pass
assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("winter");
assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("coming", "winter");
// assertions will fail
assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("Lannister");
assertThat(newArrayList("Aria", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark");
assertThat(newArrayList("Aria", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark", "Lannister", "Aria");
containsOnlyOnce
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
values
- the given values.this
assertion object.public S containsExactly(T... values)
HashSet
, prefer ObjectEnumerableAssert.containsOnly(Object...)
in that case).
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass
assertThat(elvesRings).containsExactly(vilya, nenya, narya);
// assertion will fail as actual and expected orders differ.
assertThat(elvesRings).containsExactly(nenya, vilya, narya);
containsExactly
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
values
- the given values.this
assertion object.public S isSubsetOf(Iterable<? extends T> values)
Iterable
.
Example:
// an Iterable is used in the example but it would also work with an array
List<Ring> ringsOfPower = newArrayList(oneRing, vilya, nenya, narya, dwarfRing, manRing);
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass:
assertThat(elvesRings).isSubsetOf(ringsOfPower);
// assertions will fail:
assertThat(elvesRings).isSubsetOf(newArrayList(nenya, narya));
isSubsetOf
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
values
- the Iterable
that should contain all actual elements.public S containsSequence(T... sequence)
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass
assertThat(elvesRings).containsSequence(vilya, nenya);
// assertions will fail
assertThat(elvesRings).containsSequence(vilya, narya);
assertThat(elvesRings).containsSequence(nenya, vilya);
containsSequence
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
sequence
- the sequence of objects to look for.public S containsSubsequence(T... sequence)
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass
assertThat(elvesRings).containsSubsequence(vilya, nenya);
assertThat(elvesRings).containsSubsequence(vilya, narya);
// assertion will fail
assertThat(elvesRings).containsSubsequence(nenya, vilya);
containsSubsequence
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
sequence
- the sequence of objects to look for.public S doesNotContain(T... values)
ObjectEnumerableAssert
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertion will pass
assertThat(abc).doesNotContain("d", "e");
doesNotContain
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
values
- the given values.this
assertion object.public S doesNotContainAnyElementsOf(Iterable<? extends T> iterable)
ObjectEnumerableAssert
Iterable
(i.e. none).
Example:
// an Iterable is used in the example but it would also work with an array
// These assertions succeed:
List<String> actual = newArrayList("GIT", "CVS", "SOURCESAFE");
List<String> values = newArrayList("git", "cvs", "subversion");
assertThat(actual).doesNotContainAnyElementsOf(values);
// These fail:
List<String> actual = newArrayList("GIT", "cvs", "SOURCESAFE");
List<String> values = newArrayList("git", "cvs", "subversion");
assertThat(actual).doesNotContainAnyElementsOf(values);
doesNotContainAnyElementsOf
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
iterable
- the Iterable
whose elements must not be in the actual group.this
assertion object.public S doesNotHaveDuplicates()
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> lotsOfAs = newArrayList("a", "a", "a");
// assertion will pass
assertThat(abc).doesNotHaveDuplicates();
// assertion will fail
assertThat(lotsOfAs).doesNotHaveDuplicates();
doesNotHaveDuplicates
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
this
assertion object.public S startsWith(T... sequence)
ObjectEnumerableAssert.containsSequence(Object...)
, but it also verifies that the first element in the
sequence is also first element of the actual group.
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertion will pass
assertThat(abc).startsWith("a", "b");
// assertion will fail
assertThat(abc).startsWith("c");
startsWith
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
sequence
- the sequence of objects to look for.public S endsWith(T... sequence)
ObjectEnumerableAssert.containsSequence(Object...)
, but it also verifies that the last element in the
sequence is also last element of the actual group.
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
// assertion will pass
assertThat(abc).endsWith("b", "c");
// assertion will fail
assertThat(abc).endsWith("a");
endsWith
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
sequence
- the sequence of objects to look for.public S containsNull()
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abNull = newArrayList("a", "b", null);
// assertion will pass
assertThat(abNull).containsNull();
// assertion will fail
assertThat(abc).containsNull();
containsNull
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
this
assertion object.public S doesNotContainNull()
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abNull = newArrayList("a", "b", null);
// assertion will pass
assertThat(abc).doesNotContainNull();
// assertion will fail
assertThat(abNull).doesNotContainNull();
doesNotContainNull
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
this
assertion object.public S are(Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
Condition<String> singleCharacterString = new Condition<String>() {
public boolean matches(String value) {
return value.length() == 1;
}
});
// assertion will pass
assertThat(abc).are(singleCharacterString);
// assertion will fail
assertThat(abcc).are(singleCharacterString);
are
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
condition
- the given condition.this
object.public S areNot(Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
Condition<String> longerThanOneCharacter = new Condition<String>() {
public boolean matches(String value) {
return value.length() > 1;
}
});
// assertion will pass
assertThat(abc).areNot(longerThanOneCharacter);
// assertion will fail
assertThat(abcc).areNot(longerThanOneCharacter);
areNot
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
condition
- the given condition.this
object.public S have(Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
Condition<String> singleCharacterStringOnly = new Condition<String>() {
public boolean matches(String value) {
return value.length() == 1;
}
});
// assertion will pass
assertThat(abc).have(singleCharacterStringOnly);
// assertion will fail
assertThat(abcc).have(singleCharacterStringOnly);
have
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
condition
- the given condition.this
object.public S doNotHave(Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> abcc = newArrayList("a", "b", "cc");
Condition<String> longerThanOneCharacterString = new Condition<String>() {
public boolean matches(String value) {
return value.length() > 1;
}
});
// assertion will pass
assertThat(abc).doNotHave(longerThanOneCharacterString);
// assertion will fail
assertThat(abcc).doNotHave(longerThanOneCharacterString);
doNotHave
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
condition
- the given condition.this
object.public S areAtLeastOne(Condition<? super T> condition)
areAtLeast(1, condition)
.
Example:
// an Iterable is used in the example but it would also work with an array
// jedi is a Condition<String>
assertThat(newLinkedHashSet("Luke", "Solo", "Leia")).areAtLeastOne(jedi);
areAtLeastOne
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
ObjectEnumerableAssert.haveAtLeast(int, Condition)
public S areAtLeast(int times, Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> odd = new Condition<Integer>() {
public boolean matches(Integer value) {
return value % 2 == 1;
}
});
// assertion will pass
oneTwoThree.areAtLeast(2, odd);
// assertion will fail
oneTwoThree.areAtLeast(3, odd);
areAtLeast
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
times
- the minimum number of times the condition should be verified.condition
- the given condition.this
object.public S areAtMost(int times, Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> odd = new Condition<Integer>() {
public boolean matches(Integer value) {
return value % 2 == 1;
}
});
// assertions will pass
oneTwoThree.areAtMost(2, odd);
oneTwoThree.areAtMost(3, odd);
// assertions will fail
oneTwoThree.areAtMost(1, odd);
areAtMost
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
times
- the number of times the condition should be at most verified.condition
- the given condition.this
object.public S areExactly(int times, Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> odd = new Condition<Integer>() {
public boolean matches(Integer value) {
return value % 2 == 1;
}
});
// assertion will pass
oneTwoThree.areExactly(2, odd);
// assertions will fail
oneTwoThree.areExactly(1, odd);
oneTwoThree.areExactly(3, odd);
areExactly
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
times
- the exact number of times the condition should be verified.condition
- the given condition.this
object.public S haveAtLeastOne(Condition<? super T> condition)
haveAtLeast(1, condition)
.
Example:
// an Iterable is used in the example but it would also work with an array
List<BasketBallPlayer> bullsPlayers = newArrayList(noah, rose);
// potentialMvp is a Condition<BasketBallPlayer>
assertThat(bullsPlayers).haveAtLeastOne(potentialMvp);
haveAtLeastOne
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
ObjectEnumerableAssert.haveAtLeast(int, Condition)
public S haveAtLeast(int times, Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> odd = new Condition<Integer>() {
public boolean matches(Integer value) {
return value % 2 == 1;
}
});
// assertion will pass
oneTwoThree.haveAtLeast(2, odd);
// assertion will fail
oneTwoThree.haveAtLeast(3, odd);
This method is an alias for ObjectEnumerableAssert.areAtLeast(int, Condition)
.haveAtLeast
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
public S haveAtMost(int times, Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> odd = new Condition<Integer>() {
public boolean matches(Integer value) {
return value % 2 == 1;
}
});
// assertions will pass
oneTwoThree.haveAtMost(2, odd);
oneTwoThree.haveAtMost(3, odd);
// assertion will fail
oneTwoThree.haveAtMost(1, odd);
This method is an alias ObjectEnumerableAssert.areAtMost(int, Condition)
.haveAtMost
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
public S haveExactly(int times, Condition<? super T> condition)
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3);
Condition<Integer> odd = new Condition<Integer>() {
public boolean matches(Integer value) {
return value % 2 == 1;
}
});
// assertion will pass
oneTwoThree.haveExactly(2, odd);
// assertions will fail
oneTwoThree.haveExactly(1, odd);
oneTwoThree.haveExactly(3, odd);
This method is an alias ObjectEnumerableAssert.areExactly(int, Condition)
.haveExactly
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
public S hasAtLeastOneElementOfType(Class<?> expectedType)
Iterable
belong to the specified type (matching includes
subclasses of the given type).
Example:
List<Number> numbers = new ArrayList<Number>();
numbers.add(1);
numbers.add(2L);
// successful assertion:
assertThat(numbers).hasAtLeastOneElementOfType(Long.class);
// assertion failure:
assertThat(numbers).hasAtLeastOneElementOfType(Float.class);
hasAtLeastOneElementOfType
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
expectedType
- the expected type.NullPointerException
- if the given type is null
.AssertionError
- if the actual Object
group does not have any elements of the given type.public S hasOnlyElementsOfType(Class<?> expectedType)
Iterable
belong to the specified type (matching includes
subclasses of the given type).
Example:
List<Number> numbers = new ArrayList<Number>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
// successful assertion:
assertThat(numbers).hasOnlyElementsOfType(Number.class);
assertThat(numbers).hasOnlyElementsOfType(Integer.class);
// assertion failure:
assertThat(numbers).hasOnlyElementsOfType(Long.class);
hasOnlyElementsOfType
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
expectedType
- the expected type.NullPointerException
- if the given type is null
.AssertionError
- if one element is not of the expected type.public S containsAll(Iterable<? extends T> iterable)
Iterable
, in any order.
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<String> abc = newArrayList("a", "b", "c");
Iterable<String> cb = newArrayList("c", "b");
// assertion will pass
assertThat(abc).containsAll(cb);
containsAll
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
iterable
- the given Iterable
we will get elements from.this
assertion object.public S usingElementComparator(Comparator<? super T> elementComparator)
equals
method to compare group
elements for
incoming assertion checks.
Custom comparator is bound to assertion instance, meaning that if a new assertion is created, it will use default comparison strategy.
Examples :
// compares invoices by payee
assertThat(invoiceList).usingComparator(invoicePayeeComparator).isEqualTo(expectedInvoiceList).
// compares invoices by date, doesNotHaveDuplicates and contains both use the given invoice date comparator
assertThat(invoiceList).usingComparator(invoiceDateComparator).doesNotHaveDuplicates().contains(may2010Invoice)
// as assertThat(invoiceList) creates a new assertion, it falls back to standard comparison strategy
// based on Invoice's equal method to compare invoiceList elements to lowestInvoice.
assertThat(invoiceList).contains(lowestInvoice).
// standard comparison : the fellowshipOfTheRing includes Gandalf but not Sauron (believe me) ...
assertThat(fellowshipOfTheRing).contains(gandalf)
.doesNotContain(sauron);
// ... but if we compare only races, Sauron is in fellowshipOfTheRing because he's a Maia like Gandalf.
assertThat(fellowshipOfTheRing).usingElementComparator(raceComparator)
.contains(sauron);
usingElementComparator
in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
elementComparator
- the comparator to use for incoming assertion checks.this
assertion object.public S usingDefaultElementComparator()
This method should be used to disable a custom comparison strategy set by calling
EnumerableAssert.usingElementComparator(Comparator)
.
usingDefaultElementComparator
in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
this
assertion object.public ListAssert<Object> extracting(String propertyOrField)
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify the names of TolkienCharacter in fellowshipOfTheRing :
assertThat(fellowshipOfTheRing).extracting("name")
.contains("Boromir", "Gandalf", "Frodo")
.doesNotContain("Sauron", "Elrond");
// you can extract nested property/field like the name of Race :
assertThat(fellowshipOfTheRing).extracting("race.name")
.contains("Hobbit", "Elf")
.doesNotContain("Orc");
A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked
for, if the field does not exist an IntrospectionError
is thrown, by default private fields are read but
you can change this with Assertions.setAllowComparingPrivateFields(boolean)
, trying to read a private field
when it's not allowed leads to an IntrospectionError
.
It only works if all objects have the field or all objects have the property with the given name, i.e. it
won't work if half of the objects have the field and the other the property.
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet
, you won't be able to make any assumptions on the extracted values
order.
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee luke = new Employee(2L, new Name("Luke"), 22);
Employee han = new Employee(3L, new Name("Han"), 31);
// build two maps
Map<String, Employee> map1 = new HashMap<>();
map1.put("key1", yoda);
map1.put("key2", luke);
Map<String, Employee> map2 = new HashMap<>();
map2.put("key1", yoda);
map2.put("key2", han);
// instead of a list of objects, we have a list of maps
List<Map<String, Employee>> maps = asList(map1, map2);
// extracting a property in that case = get values from maps using property as a key
assertThat(maps).extracting("key2").containsExactly(luke, han);
assertThat(maps).extracting("key1").containsExactly(yoda, yoda);
// type safe version
assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);
// it works with several keys, extracted values being wrapped in a Tuple
assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));
// unknown keys leads to null (map behavior)
assertThat(maps).extracting("bad key").containsExactly(null, null);
propertyOrField
- the property/field to extract from the elements of the Iterable under testIntrospectionError
- if no field or property exists with the given name (or field exists but is not public)
in one of the initial Iterable's element.public ListAssert<Object> extractingResultOf(String method)
// Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()
List<WesterosHouse> greatHouses = new ArrayList<WesterosHouse>();
greatHouses.add(new WesterosHouse("Stark", "Winter is Coming"));
greatHouses.add(new WesterosHouse("Lannister", "Hear Me Roar!"));
greatHouses.add(new WesterosHouse("Greyjoy", "We Do Not Sow"));
greatHouses.add(new WesterosHouse("Baratheon", "Our is the Fury"));
greatHouses.add(new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"));
greatHouses.add(new WesterosHouse("Tyrell", "Growing Strong"));
// let's verify the words of great houses in Westeros:
assertThat(greatHouses).extractingResultOf("sayTheWords")
.contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar")
.doesNotContain("Lannisters always pay their debts");
Following requirements have to be met to extract method results:
HashSet
, you won't be able to make any assumptions on the extracted results order.method
- the name of the method which result is to be extracted from the array under testIllegalArgumentException
- if no method exists with the given name, or method is not public, or method does
return void, or method accepts arguments.public <P> ListAssert<P> extractingResultOf(String method, Class<P> extractedType)
// Build a array of WesterosHouse, a WesterosHouse has a method: public String sayTheWords()
List<WesterosHouse> greatHouses = new ArrayList<WesterosHouse>();
greatHouses.add(new WesterosHouse("Stark", "Winter is Coming"));
greatHouses.add(new WesterosHouse("Lannister", "Hear Me Roar!"));
greatHouses.add(new WesterosHouse("Greyjoy", "We Do Not Sow"));
greatHouses.add(new WesterosHouse("Baratheon", "Our is the Fury"));
greatHouses.add(new WesterosHouse("Martell", "Unbowed, Unbent, Unbroken"));
greatHouses.add(new WesterosHouse("Tyrell", "Growing Strong"));
// let's verify the words of great houses in Westeros:
assertThat(greatHouses).extractingResultOf("sayTheWords", String.class)
.contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar")
.doesNotContain("Lannisters always pay their debts");
Following requirements have to be met to extract method results:
HashSet
, you won't be able to make any assumptions of the extracted values
order.method
- the name of the method which result is to be extracted from the array under testextractedType
- type of element of the extracted ListIllegalArgumentException
- if no method exists with the given name, or method is not public, or method does
return void or method accepts arguments.public <P> ListAssert<P> extracting(String propertyOrField, Class<P> extractingType)
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify the names of TolkienCharacter in fellowshipOfTheRing :
assertThat(fellowshipOfTheRing).extracting("name", String.class)
.contains("Boromir", "Gandalf", "Frodo")
.doesNotContain("Sauron", "Elrond");
// you can extract nested property/field like the name of Race :
assertThat(fellowshipOfTheRing).extracting("race.name", String.class)
.contains("Hobbit", "Elf")
.doesNotContain("Orc");
A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked
for, if the field does not exist an IntrospectionError
is thrown, by default private fields are read but
you can change this with Assertions.setAllowComparingPrivateFields(boolean)
, trying to read a private field
when it's not allowed leads to an IntrospectionError
.
It only works if all objects have the field or all objects have the property with the given name, i.e. it
won't work if half of the objects have the field and the other the property.
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet
, you won't be able to make any assumptions on the extracted values
order.
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee luke = new Employee(2L, new Name("Luke"), 22);
Employee han = new Employee(3L, new Name("Han"), 31);
// build two maps
Map<String, Employee> map1 = new HashMap<>();
map1.put("key1", yoda);
map1.put("key2", luke);
Map<String, Employee> map2 = new HashMap<>();
map2.put("key1", yoda);
map2.put("key2", han);
// instead of a list of objects, we have a list of maps
List<Map<String, Employee>> maps = asList(map1, map2);
// extracting a property in that case = get values from maps using property as a key
assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han);
// non type safe version
assertThat(maps).extracting("key2").containsExactly(luke, han);
assertThat(maps).extracting("key1").containsExactly(yoda, yoda);
// it works with several keys, extracted values being wrapped in a Tuple
assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));
// unknown keys leads to null (map behavior)
assertThat(maps).extracting("bad key").containsExactly(null, null);
propertyOrField
- the property/field to extract from the Iterable under testextractingType
- type to returnIntrospectionError
- if no field or property exists with the given name (or field exists but is not public)
in one of the initial Iterable's element.public ListAssert<Tuple> extracting(String... propertiesOrFields)
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify 'name' and 'age' of some TolkienCharacter in fellowshipOfTheRing :
assertThat(fellowshipOfTheRing).extracting("name", "age")
.contains(tuple("Boromir", 37),
tuple("Sam", 38),
tuple("Legolas", 1000));
// extract 'name', 'age' and Race name values.
assertThat(fellowshipOfTheRing).extracting("name", "age", "race.name")
.contains(tuple("Boromir", 37, "Man"),
tuple("Sam", 38, "Hobbit"),
tuple("Legolas", 1000, "Elf"));
A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked
for, if the field does not exist an IntrospectionError
is thrown, by default private fields are read but
you can change this with Assertions.setAllowComparingPrivateFields(boolean)
, trying to read a private field
when it's not allowed leads to an IntrospectionError
.
It only works if all objects have the field or all objects have the property with the given name, i.e. it
won't work if half of the objects have the field and the other the property.
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet
, you won't be able to make any assumptions on the extracted values
order.
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee luke = new Employee(2L, new Name("Luke"), 22);
Employee han = new Employee(3L, new Name("Han"), 31);
// build two maps
Map<String, Employee> map1 = new HashMap<>();
map1.put("key1", yoda);
map1.put("key2", luke);
Map<String, Employee> map2 = new HashMap<>();
map2.put("key1", yoda);
map2.put("key2", han);
// instead of a list of objects, we have a list of maps
List<Map<String, Employee>> maps = asList(map1, map2);
// extracting a property in that case = get values from maps using property as a key
assertThat(maps).extracting("key2").containsExactly(luke, han);
assertThat(maps).extracting("key1").containsExactly(yoda, yoda);
// it works with several keys, extracted values being wrapped in a Tuple
assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han));
// unknown keys leads to null (map behavior)
assertThat(maps).extracting("bad key").containsExactly(null, null);
propertiesOrFields
- the properties/fields to extract from the elements of the Iterable under testIntrospectionError
- if one of the given name does not match a field or property (or field exists but is not
public) in one of the initial Iterable's element.public <V> ListAssert<V> extracting(Extractor<? super T,V> extractor)
extracting(String)
, as it
doesn't utilize introspection.
Let's have a look at an example :
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// this extracts the race
Extractor<TolkienCharacter, Race> race = new Extractor<TolkienCharacter, Race>() {
@Override
public Race extract(TolkienCharacter input) {
return input.getRace();
}
}
// fellowship has hobbitses, right, my presioussss?
assertThat(fellowshipOfTheRing).extracting(race).contains(HOBBIT);
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under
test, for example if it's a HashSet
, you won't be able to make any assumptions on the extracted values
order.extractor
- the object transforming input object to desired onepublic <V> ListAssert<V> flatExtracting(Extractor<? super T,? extends Collection<V>> extractor)
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);
Extractor<CartoonCharacter, List<CartoonCharacter>> childrenOf = new Extractor<CartoonChildren, List<CartoonChildren>>() {
@Override
public List<CartoonChildren> extract(CartoonCharacter input) {
return input.getChildren();
}
}
List<CartoonCharacter> parents = newArrayList(homer, fred);
// check children
assertThat(parent).flatExtracting(childrenOf)
.containsOnly(bart, lisa, maggie, pebbles);
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted
collections.extractor
- the object transforming input object to an Iterable of desired onespublic ListAssert<Object> flatExtracting(String propertyName)
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);
List<CartoonCharacter> parents = newArrayList(homer, fred);
// check children
assertThat(parents).flatExtracting("children")
.containsOnly(bart, lisa, maggie, pebbles);
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted
collections.propertyName
- the object transforming input object to an Iterable of desired onesIllegalArgumentException
- if one of the extracted property value was not an array or an iterable.@SafeVarargs public final ListAssert<Tuple> extracting(java.util.function.Function<T,?>... extractors)
Function
s to extract the values from the Iterable's elements under test into a new Iterable
composed of Tuple
(a simple data structure containing th extracted values), this new Iterable becoming the
Iterable under test.
It allows you to test values from the Iterable's elements instead of testing the elements themselves, it can be
sometimes much less work!
The Tuple data corresponds to the extracted values from the Iterable's elements, for instance if you pass functions
extracting "id", "name" and "email" values then each Tuple data will be composed of an id, a name and an email
extracted from the element of the initial Iterable (the Tuple's data order is the same as the given functions
order).
Let's take an example to make things clearer :
// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
// they can be public field or properties, both can be extracted.
List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
// let's verify 'name', 'age' and Race of some TolkienCharacter in fellowshipOfTheRing :
assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getName,
character -> character.getAge(),
TolkienCharacter::getRace)
.containsOnly(tuple("Frodo", 33, HOBBIT),
tuple("Sam", 38, HOBBIT),
tuple("Gandalf", 2020, MAIA),
tuple("Legolas", 1000, ELF),
tuple("Pippin", 28, HOBBIT),
tuple("Gimli", 139, DWARF),
tuple("Aragorn", 87, MAN),
tuple("Boromir", 37, MAN));
You can use lambda expression or a method reference to extract the expected values.
Use Tuple.tuple(Object...)
to initialize the expected values.
Note that the order of the extracted tuples list is consistent with the iteration order of the Iterable under test,
for example if it's a HashSet
, you won't be able to make any assumptions on the extracted tuples order.extractors
- the extractor functions to extract a value from an element of the Iterable under test.public S containsExactlyElementsOf(Iterable<? extends T> iterable)
containsExactly(Object[])
but handle the Iterable
to array conversion. Same semantic as
containsExactly(Object...)
: verifies that actual contains all the elements of the given iterable and
nothing else in the same order.
Example :
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertion will pass
assertThat(elvesRings).containsExactly(newLinkedList(vilya, nenya, narya));
// assertion will fail as actual and expected orders differ.
assertThat(elvesRings).containsExactly(newLinkedList(nenya, vilya, narya));
containsExactlyElementsOf
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
iterable
- the given Iterable
we will get elements from.public S containsOnlyElementsOf(Iterable<? extends T> iterable)
ObjectEnumerableAssert.containsOnly(Object[])
: verifies that actual contains all the elements of the given
iterable and nothing else, in any order.
Example :
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> rings = newArrayList(nenya, vilya);
// assertion will pass
assertThat(rings).containsOnlyElementsOf(newLinkedList(nenya, vilya));
assertThat(rings).containsOnlyElementsOf(newLinkedList(nenya, nenya, vilya, vilya));
// assertion will fail as actual does not contain narya.
assertThat(rings).containsOnlyElementsOf(newLinkedList(nenya, vilya, narya));
// assertion will fail as actual contain nenya.
assertThat(rings).containsOnlyElementsOf(newLinkedList(vilya));
containsOnlyElementsOf
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
iterable
- the given Iterable
we will get elements from.public S hasSameElementsAs(Iterable<? extends T> iterable)
ObjectEnumerableAssert.containsOnlyElementsOf(Iterable)
: verifies that actual contains all the elements of the
given iterable and nothing else, in any order.
Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
// assertions will pass:
assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya, vilya));
assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya, vilya, nenya));
// assertions will fail:
assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya));
assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya, vilya, oneRing));
hasSameElementsAs
in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
iterable
- the Iterable whose elements we expect to be presentpublic S usingFieldByFieldElementComparator()
equals
method to compare group elements for incoming assertion checks. Private fields
are included but this can be disabled using Assertions.setAllowExtractingPrivateFields(boolean)
.
This can be handy if equals
method of the objects to compare does not suit you.
Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared
to the other field/property using its equals
method.
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);
// Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references
assertThat(newArrayList(frodo)).contains(frodoClone);
// frodo and frodoClone are equals when doing a field by field comparison.
assertThat(newArrayList(frodo)).usingFieldByFieldElementComparator().contains(frodoClone);
this
assertion object.public S usingElementComparatorOnFields(String... fields)
equals
method to compare group elements for
incoming assertion checks. Private fields are included but this can be disabled using
Assertions.setAllowExtractingPrivateFields(boolean)
.
This can be handy if equals
method of the objects to compare does not suit you.
Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared
to the other field/property using its equals
method.
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);
// frodo and sam both are hobbits, so they are equals when comparing only race
assertThat(newArrayList(frodo)).usingElementComparatorOnFields("race").contains(sam); // OK
// ... but not when comparing both name and race
assertThat(newArrayList(frodo)).usingElementComparatorOnFields("name", "race").contains(sam); // FAIL
this
assertion object.protected S usingComparisonStrategy(ComparisonStrategy comparisonStrategy)
public S usingElementComparatorIgnoringFields(String... fields)
equals
method to compare group elements for
incoming assertion checks. Private fields are included but this can be disabled using
Assertions.setAllowExtractingPrivateFields(boolean)
.
This can be handy if equals
method of the objects to compare does not suit you.
Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared
to the other field/property using its equals
method.
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT);
// frodo and sam both are hobbits, so they are equals when comparing only race (i.e. ignoring all other fields)
assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("name", "age").contains(sam); // OK
// ... but not when comparing both name and race
assertThat(newArrayList(frodo)).usingElementComparatorIgnoringFields("age").contains(sam); // FAIL
this
assertion object.public S inHexadecimal()
final List<Byte> bytes = newArrayList((byte) 0x10, (byte) 0x20);
With standard error message:
assertThat(bytes).contains((byte)0x30);
Expecting:
<[16, 32]>
to contain:
<[48]>
but could not find:
<[48]>
With Hexadecimal error message:
assertThat(bytes).inHexadecimal().contains((byte)0x30);
Expecting:
<[0x10, 0x20]>
to contain:
<[0x30]>
but could not find:
<[0x30]>
inHexadecimal
in class AbstractAssert<S extends AbstractIterableAssert<S,A,T>,A extends Iterable<? extends T>>
this
assertion object.public S inBinary()
final List<Byte> bytes = newArrayList((byte) 0x10, (byte) 0x20);
With standard error message:
assertThat(bytes).contains((byte)0x30);
Expecting:
<[16, 32]>
to contain:
<[48]>
but could not find:
<[48]>
With binary error message:
assertThat(bytes).inBinary().contains((byte)0x30);
Expecting:
<[0b00010000, 0b00100000]>
to contain:
<[0b00110000]>
but could not find:
<[0b00110000]>
inBinary
in class AbstractAssert<S extends AbstractIterableAssert<S,A,T>,A extends Iterable<? extends T>>
this
assertion object.public S filteredOn(String propertyOrFieldName, Object expectedValue)
expectedValue
, the
property/field is specified by propertyOrFieldName
parameter.
The filter first tries to get the value from a property (named propertyOrFieldName
), if no such property
exists it tries to read the value from a field. Reading private fields is supported by default, this can be
globally disabled by calling Assertions.setAllowExtractingPrivateFields(false)
.
When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check all employees 800 years old (yes, special employees):
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
Employee noname = new Employee(4L, null, 50);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
assertThat(employees).filteredOn("age", 800)
.containsOnly(yoda, obiwan);
Nested properties/fields are supported:
// Name is bean class with 'first' and 'last' String properties
// name is null for noname => it does not match the filter on "name.first"
assertThat(employees).filteredOn("name.first", "Luke")
.containsOnly(luke);
assertThat(employees).filteredOn("name.last", "Vader")
.isEmpty();
If you want to filter on null value, use filteredOnNull(String)
as Java will resolve the call to
filteredOn(String, FilterOperator)
instead of this method.
An IntrospectionError
is thrown if the given propertyOrFieldName can't be found in one of the iterable
elements.
You can chain filters:
// fellowshipOfTheRing is a list of TolkienCharacter having race and name fields
// 'not' filter is statically imported from Assertions.not
assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")
.filteredOn("name", not("Boromir"))
.containsOnly(aragorn);
If you need more complex filter, use filteredOn(Predicate)
or filteredOn(Condition)
.propertyOrFieldName
- the name of the property or field to readexpectedValue
- the value to compare element's property or field withIllegalArgumentException
- if the given propertyOrFieldName is null
or empty.IntrospectionError
- if the given propertyOrFieldName can't be found in one of the iterable elements.public S filteredOnNull(String propertyOrFieldName)
propertyOrFieldName
is null.
The filter first tries to get the value from a property (named propertyOrFieldName
), if no such property
exists it tries to read the value from a field. Reading private fields is supported by default, this can be
globally disabled by calling Assertions.setAllowExtractingPrivateFields(false)
.
When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check all employees 800 years old (yes, special employees):
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
Employee noname = new Employee(4L, null, 50);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
assertThat(employees).filteredOnNull("name")
.containsOnly(noname);
Nested properties/fields are supported:
// Name is bean class with 'first' and 'last' String properties
assertThat(employees).filteredOnNull("name.last")
.containsOnly(yoda, obiwan, noname);
An IntrospectionError
is thrown if the given propertyOrFieldName can't be found in one of the iterable
elements.
If you need more complex filter, use filteredOn(Predicate)
or filteredOn(Condition)
.
propertyOrFieldName
- the name of the property or field to readIntrospectionError
- if the given propertyOrFieldName can't be found in one of the iterable elements.public S filteredOn(String propertyOrFieldName, FilterOperator<?> filterOperator)
FilterOperator
, the property/field is specified by propertyOrFieldName
parameter.
The existing filters are :
Whatever filter is applied, it first tries to get the value from a property (named propertyOrFieldName
), if
no such property exists it tries to read the value from a field. Reading private fields is supported by default,
this can be globally disabled by calling Assertions.setAllowExtractingPrivateFields(false)
.
When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check stuff on some special employees :
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
// 'not' filter is statically imported from Assertions.not
assertThat(employees).filteredOn("age", not(800))
.containsOnly(luke);
// 'in' filter is statically imported from Assertions.in
// Name is bean class with 'first' and 'last' String properties
assertThat(employees).filteredOn("name.first", in("Yoda", "Luke"))
.containsOnly(yoda, luke);
// 'notIn' filter is statically imported from Assertions.notIn
assertThat(employees).filteredOn("name.first", notIn("Yoda", "Luke"))
.containsOnly(obiwan);
An IntrospectionError
is thrown if the given propertyOrFieldName can't be found in one of the iterable
elements.
Note that combining filter operators is not supported, thus the following code is not correct:
// Combining filter operators like not(in(800)) is NOT supported
// -> throws UnsupportedOperationException
assertThat(employees).filteredOn("age", not(in(800)))
.contains(luke);
You can chain filters:
// fellowshipOfTheRing is a list of TolkienCharacter having race and name fields
// 'not' filter is statically imported from Assertions.not
assertThat(fellowshipOfTheRing).filteredOn("race.name", "Man")
.filteredOn("name", not("Boromir"))
.containsOnly(aragorn);
If you need more complex filter, use filteredOn(Predicate)
or filteredOn(Condition)
.propertyOrFieldName
- the name of the property or field to readfilterOperator
- the filter operator to applyIllegalArgumentException
- if the given propertyOrFieldName is null
or empty.public S filteredOn(Condition<? super T> condition)
Condition
.
If you prefer Predicate
over Condition
, use filteredOn(Predicate)
.
Example : check old employees whose age > 100:
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
Employee noname = new Employee(4L, null, 50);
List<Employee> employees = newArrayList(yoda, luke, obiwan, noname);
// old employee condition, "old employees" describes the condition in error message
// you just have to implement 'matches' method
Condition<Employee> oldEmployees = new Condition<Employee>("old employees") {
@Override
public boolean matches(Employee employee) {
return employee.getAge() > 100;
}
};
}
assertThat(employees).filteredOn(oldEmployees)
.containsOnly(yoda, obiwan);
You can combine Condition
with condition operator like Not
:
// 'not' filter is statically imported from Assertions.not
assertThat(employees).filteredOn(not(oldEmployees))
.contains(luke, noname);
condition
- the filter condition / predicateIllegalArgumentException
- if the given condition is null
.public S filteredOn(java.util.function.Predicate<? super T> predicate)
Predicate
.
Example : check old employees whose age > 100:
Employee yoda = new Employee(1L, new Name("Yoda"), 800);
Employee obiwan = new Employee(2L, new Name("Obiwan"), 800);
Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26);
List<Employee> employees = newArrayList(yoda, luke, obiwan);
assertThat(employees).filteredOn(employee -> employee.getAge() > 100)
.containsOnly(yoda, obiwan);
predicate
- the filter predicateIllegalArgumentException
- if the given predicate is null
.Copyright © 2014-2015 AssertJ. All Rights Reserved.