org.assertj.core.api
Class AbstractIterableAssert<S extends AbstractIterableAssert<S,A,T>,A extends Iterable<? extends T>,T>

java.lang.Object
  extended by org.assertj.core.api.AbstractAssert<S,A>
      extended by org.assertj.core.api.AbstractIterableAssert<S,A,T>
Type Parameters:
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.
All Implemented Interfaces:
Assert<S,A>, Descriptable<S>, EnumerableAssert<S,T>, ExtensionPoints<S,A>, ObjectEnumerableAssert<S,T>
Direct Known Subclasses:
AbstractListAssert, IterableAssert

public abstract class AbstractIterableAssert<S extends AbstractIterableAssert<S,A,T>,A extends Iterable<? extends T>,T>
extends AbstractAssert<S,A>
implements ObjectEnumerableAssert<S,T>

Base class for implementations of ObjectEnumerableAssert whose actual value type is Collection.

Author:
Yvonne Wang, Alex Ruiz, Mathieu Baechler, Joel Costigliola, Maciej Jaskowski, Nicolas François, Mikhail Mazursky, Mateusz Haligowski

Field Summary
 
Fields inherited from class org.assertj.core.api.AbstractAssert
actual, info, myself
 
Constructor Summary
protected AbstractIterableAssert(A actual, Class<?> selfType)
           
 
Method Summary
 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 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 array 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 the actual group 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 each element value does not 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(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.
<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.
 S hasAtLeastOneElementOfType(Class<?> type)
          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<?> type)
          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)
          Same semantic as 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 each element value satisfies 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)
          This method is an alias ObjectEnumerableAssert.areAtMost(int, Condition).
 S haveExactly(int times, Condition<? super T> condition)
          This method is an alias ObjectEnumerableAssert.areExactly(int, 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 the actual Iterable 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 by field comparison on all fields except the given ones (fields can be inherited fields) instead of relying on actual type A equals method to compare group elements for incoming assertion checks.
 S usingElementComparatorOnFields(String... fields)
          Use field by field comparison on the given fields only (fields can be inherited fields) instead of relying on actual type A equals method to compare group elements for incoming assertion checks.
 S usingFieldByFieldElementComparator()
          Use field by field comparison (including inherited fields) instead of relying on actual type A equals method to compare group elements for incoming assertion checks.
 
Methods inherited from class org.assertj.core.api.AbstractAssert
as, as, describedAs, describedAs, descriptionText, doesNotHave, doesNotHaveSameClassAs, equals, failWithMessage, getWritableAssertionInfo, has, hashCode, hasSameClassAs, is, isEqualTo, isExactlyInstanceOf, isIn, isIn, isInstanceOf, isInstanceOfAny, isNot, isNotEqualTo, isNotExactlyInstanceOf, isNotIn, isNotIn, isNotInstanceOf, isNotInstanceOfAny, isNotNull, isNotOfAnyClassIn, isNotSameAs, isNull, isOfAnyClassIn, isSameAs, overridingErrorMessage, usingComparator, usingDefaultComparator
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

AbstractIterableAssert

protected AbstractIterableAssert(A actual,
                                 Class<?> selfType)
Method Detail

isNullOrEmpty

public void isNullOrEmpty()
Verifies that the actual group of values is null or empty.

Specified by:
isNullOrEmpty in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>

isEmpty

public void isEmpty()
Verifies that the actual group of values is empty.

Specified by:
isEmpty in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>

isNotEmpty

public S isNotEmpty()
Verifies that the actual group of values is not empty.

Specified by:
isNotEmpty in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Returns:
this assertion object.

hasSize

public S hasSize(int expected)
Verifies that the number of values in the actual group is equal to the given one.

Specified by:
hasSize in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
expected - the expected number of values in the actual group.
Returns:
this assertion object.

hasSameSizeAs

public S hasSameSizeAs(Object other)
Verifies that the actual group has the same size as given array.

Parameter is declared as Object to accept both Object[] and primitive arrays (e.g. int[]).

Specified by:
hasSameSizeAs in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
other - the array to compare size with actual group.
Returns:
this assertion object.

hasSameSizeAs

public S hasSameSizeAs(Iterable<?> other)
Verifies that the actual group has the same size as given Iterable.

Specified by:
hasSameSizeAs in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
other - the Iterable to compare size with actual group.
Returns:
this assertion object.

contains

public S contains(T... values)
Verifies that the actual group contains the given values, in any order.

Specified by:
contains in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
values - the given values.
Returns:
this assertion object.

containsOnly

public S containsOnly(T... values)
Verifies that the actual group contains only the given values and nothing else, in any order.

Specified by:
containsOnly in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
values - the given values.
Returns:
this assertion object.

containsOnlyOnce

public S containsOnlyOnce(T... values)
Verifies that the actual array contains the given values only once.

Examples :

 // assertion will pass
 assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("winter");
 assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("coming", "winter");
 
 // assertions will fail
 assertThat(newArrayList("Aria", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark");
 assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("Lannister");
 assertThat(newArrayList("Aria", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark", "Lannister",
                                                                                              "Aria");
 

Specified by:
containsOnlyOnce in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
values - the given values.
Returns:
this assertion object.

containsExactly

public 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. don't use it with HashSet, prefer ObjectEnumerableAssert.containsOnly(Object...) in that case).

Example :

 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);
 

Specified by:
containsExactly in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
values - the given values.
Returns:
this assertion object.

isSubsetOf

public S isSubsetOf(Iterable<? extends T> values)
Verifies that all the elements of the actual Iterable are present in the given Iterable.

Parameters:
values - the Iterable that should contain all actual elements.
Returns:
this assertion object.
Throws:
AssertionError - if the actual Iterable is null.
NullPointerException - if the given Iterable is null.
AssertionError - if the actual Iterable is not subset of set Iterable.

containsSequence

public S containsSequence(T... sequence)
Verifies that the actual group contains the given sequence, without any other values between them.

 Example:
 Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
 
 // assertion will pass
 assertThat(elvesRings).containsSequence(vilya, nenya);
 
 // assertion will fail
 assertThat(elvesRings).containsSequence(vilya, narya);
 assertThat(elvesRings).containsSequence(nenya, vilya);
 

Specified by:
containsSequence in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
sequence - the sequence of objects to look for.
Returns:
this assertion object.

containsSubsequence

public S containsSubsequence(T... sequence)
Verifies that the actual group contains the given subsequence (possibly with other values between them).

 Example:
 Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya);
 
 // assertion will pass
 assertThat(elvesRings).containsSubsequence(vilya, nenya);
 assertThat(elvesRings).containsSubsequence(vilya, narya);
 
 // assertion will fail
 assertThat(elvesRings).containsSubsequence(nenya, vilya);
 

Specified by:
containsSubsequence in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
sequence - the sequence of objects to look for.
Returns:
this assertion object.

doesNotContain

public S doesNotContain(T... values)
Description copied from interface: ObjectEnumerableAssert
Verifies that the actual group does not contain the given values.

Specified by:
doesNotContain in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
values - the given values.
Returns:
this assertion object.

doesNotContainAnyElementsOf

public S doesNotContainAnyElementsOf(Iterable<? extends T> iterable)
Verifies that the actual group does not contain any elements of the given Iterable (i.e. none).

 // this assertion succeeds :
 List<String> actual = newArrayList("GIT", "CVS", "SOURCESAFE");
 List<String> values = newArrayList("git", "cvs", "subversion");
 assertThat(actual).doesNotContainAnyElementsOf(values);
 
 // This one fails :
 List<String> actual = newArrayList("GIT", "cvs", "SOURCESAFE");
 List<String> values = newArrayList("git", "cvs", "subversion");
 assertThat(actual).doesNotContainAnyElementsOf(values);
 

Parameters:
iterable - the given Iterable
Returns:
this assertion object.
Throws:
NullPointerException - if the given argument is null.
IllegalArgumentException - if the given argument is an empty iterable.
AssertionError - if the actual group is null.
AssertionError - if the actual group contains some elements of the given Iterable.

doesNotHaveDuplicates

public S doesNotHaveDuplicates()
Verifies that the actual group does not contain duplicates.

Specified by:
doesNotHaveDuplicates in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Returns:
this assertion object.

startsWith

public S startsWith(T... sequence)
Verifies that the actual group starts with the given sequence of objects, without any other objects between them. Similar to ObjectEnumerableAssert.containsSequence(Object...), but it also verifies that the first element in the sequence is also first element of the actual group.

Specified by:
startsWith in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
sequence - the sequence of objects to look for.
Returns:
this assertion object.

endsWith

public S endsWith(T... sequence)
Verifies that the actual group ends with the given sequence of objects, without any other objects between them. Similar to ObjectEnumerableAssert.containsSequence(Object...), but it also verifies that the last element in the sequence is also last element of the actual group.

Specified by:
endsWith in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
sequence - the sequence of objects to look for.
Returns:
this assertion object.

containsNull

public S containsNull()
Verifies that the actual group contains at least a null element.

Specified by:
containsNull in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Returns:
this assertion object.

doesNotContainNull

public S doesNotContainNull()
Verifies that the actual group does not contain null elements.

Specified by:
doesNotContainNull in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Returns:
this assertion object.

are

public S are(Condition<? super T> condition)
Verifies that each element value satisfies the given condition

Specified by:
are in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
condition - the given condition.
Returns:
this object.

areNot

public S areNot(Condition<? super T> condition)
Verifies that each element value does not satisfy the given condition

Specified by:
areNot in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
condition - the given condition.
Returns:
this object.

have

public S have(Condition<? super T> condition)
Verifies that each element value satisfies the given condition

Specified by:
have in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
condition - the given condition.
Returns:
this object.

doNotHave

public S doNotHave(Condition<? super T> condition)
Verifies that each element value does not satisfy the given condition

Specified by:
doNotHave in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
condition - the given condition.
Returns:
this object.

areAtLeastOne

public S areAtLeastOne(Condition<? super T> condition)
Verifies that there is at least one element in the actual group satisfying the given condition.

This method is an alias for areAtLeast(1, condition).

Example:

 // jedi is a Condition<String>
 assertThat(newLinkedHashSet("Luke", "Solo", "Leia")).areAtLeastOne(jedi);
 

Specified by:
areAtLeastOne in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
See Also:
ObjectEnumerableAssert.haveAtLeast(int, Condition)

areAtLeast

public S areAtLeast(int times,
                    Condition<? super T> condition)
Verifies that there is at least n elements in the actual group satisfying the given condition.

Specified by:
areAtLeast in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
times - the minimum number of times the condition should be verified.
condition - the given condition.
Returns:
this object.

areAtMost

public S areAtMost(int times,
                   Condition<? super T> condition)
Verifies that there is at most n elements in the actual group satisfying the given condition.

Specified by:
areAtMost in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
times - the number of times the condition should be at most verified.
condition - the given condition.
Returns:
this object.

areExactly

public S areExactly(int times,
                    Condition<? super T> condition)
Verifies that there is exactly n elements in the actual group satisfying the given condition.

Specified by:
areExactly in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
times - the exact number of times the condition should be verified.
condition - the given condition.
Returns:
this object.

haveAtLeastOne

public S haveAtLeastOne(Condition<? super T> condition)
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:

 List<BasketBallPlayer> bullsPlayers = newArrayList(noah, rose);
 
 // potentialMvp is a Condition<BasketBallPlayer>
 assertThat(bullsPlayers).haveAtLeastOne(potentialMvp);
 

Specified by:
haveAtLeastOne in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
See Also:
ObjectEnumerableAssert.haveAtLeast(int, Condition)

haveAtLeast

public S haveAtLeast(int times,
                     Condition<? super T> condition)
Verifies that there is at least n elements in the actual group satisfying the given condition.

This method is an alias for ObjectEnumerableAssert.areAtLeast(int, Condition).

Specified by:
haveAtLeast in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>

haveAtMost

public S haveAtMost(int times,
                    Condition<? super T> condition)
This method is an alias ObjectEnumerableAssert.areAtMost(int, Condition).

Specified by:
haveAtMost in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>

haveExactly

public S haveExactly(int times,
                     Condition<? super T> condition)
This method is an alias ObjectEnumerableAssert.areExactly(int, Condition).

Specified by:
haveExactly in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>

hasAtLeastOneElementOfType

public S hasAtLeastOneElementOfType(Class<?> type)
Verifies that at least one element in the actual 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);
 

Specified by:
hasAtLeastOneElementOfType in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
expectedType - the expected type.
Returns:
this assertion object.
Throws:
NullPointerException - if the given type is null.
AssertionError - if the actual Object group does not have any elements of the given type.

hasOnlyElementsOfType

public S hasOnlyElementsOfType(Class<?> type)
Verifies that all the elements in the actual 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);
 

Specified by:
hasOnlyElementsOfType in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
expectedType - the expected type.
Returns:
this assertion object.
Throws:
NullPointerException - if the given type is null.
AssertionError - if one element is not of the expected type.

containsAll

public S containsAll(Iterable<? extends T> iterable)
Verifies that the actual group contains all the elements of given Iterable, in any order.

Specified by:
containsAll in interface ObjectEnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
iterable - the given Iterable we will get elements from.
Returns:
this assertion object.

usingElementComparator

public 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.

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);
 

Specified by:
usingElementComparator in interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Parameters:
elementComparator - the comparator to use for incoming assertion checks.
Returns:
this assertion object.

usingDefaultElementComparator

public S 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 interface EnumerableAssert<S extends AbstractIterableAssert<S,A,T>,T>
Returns:
this assertion object.

extracting

public 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.

It allows you to test a property/field of the the Iterable's elements instead of testing the elements themselves, it can be sometimes much less work !

Let's take an example to make things clearer :

 // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
 // they can be public field or properties, both can be extracted.
 List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
 
 fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
 fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
 fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
 fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
 fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
 
 // let's verify the names of TolkienCharacter in fellowshipOfTheRing :
 
 assertThat(fellowshipOfTheRing).extracting("name")
           .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 no field accessible (ie. does not exist or is not public) an IntrospectionError is thrown.

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.

Parameters:
propertyOrField - the property/field to extract from the Iterable under test
Returns:
a new assertion object whose object under test is the list of extracted property/field values.
Throws:
IntrospectionError - 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.

extractingResultOf

public 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.

It allows you to test the method results of the Iterable's elements instead of testing the elements themselves, it is especially usefull for classes that does not conform to 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()
 
 List<WesterosHouse> greatHouses = new ArrayList<WesterosHouse>();
 greatHouses.add(new WesterosHouse("Stark", "Winter is Comming"));
 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 Comming", "We Do Not Sow", "Hear Me Roar")
                        .doesNotContain("Lannisters always pay their debts");
 
Following requirements have to be met to extract method results:

Note that the order of extracted results is consistent with the iteration order of the Iterable under test, for example if it's a HashSet, you won't be able to make any assumptions on the extracted results order.

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 Iterable 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

public <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.

It allows you to test the method results of the Iterable's elements instead of testing the elements themselves, it is especially usefull for classes that does not conform to 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()
 List<WesterosHouse> greatHouses = new ArrayList<WesterosHouse>();
 greatHouses.add(new WesterosHouse("Stark", "Winter is Comming"));
 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 Comming", "We Do Not Sow", "Hear Me Roar")
                        .doesNotContain("Lannisters always pay their debts");
 
Following requirements have to be met to extract method results:

Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under test, for example if it's a HashSet, you won't be able to make any assumptions of the extracted values order.

Parameters:
method - the name of the method which result is to be extracted from the array under test
extractedType - type of element of the extracted List
Returns:
a new assertion object whose object under test is the Iterable 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.

extracting

public <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.

It allows you to test a property/field of the the Iterable's elements instead of testing the elements themselves, it can be sometimes much less work !

Let's take an example to make things clearer :

 // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
 // they can be public field or properties, both can be extracted.
 List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
 
 fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
 fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
 fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
 fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
 fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
 
 // let's verify the names of TolkienCharacter in fellowshipOfTheRing :
 
 assertThat(fellowshipOfTheRing).extracting("name", String.class)
           .contains("Boromir", "Gandalf", "Frodo")
           .doesNotContain("Sauron", "Elrond");
 
 // you can extract nested property/field like the name of Race :
 
 assertThat(fellowshipOfTheRing).extracting("race.name", String.class)
           .contains("Hobbit", "Elf")
           .doesNotContain("Orc");
 
A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked for, if no field accessible (ie. does not exist or is not public) an IntrospectionError is thrown.

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.

Parameters:
propertyOrField - the property/field to extract from the Iterable under test
extractingType - type to return
Returns:
a new assertion object whose object under test is the list of extracted property/field values.
Throws:
IntrospectionError - 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.

extracting

public 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.

It allows you to test fields/properties of the 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 of the given fields/properties, for instance if you ask to extract "id", "name" and "email" then each Tuple data will be composed of id, name and email extracted from the element of the initial Iterable (the Tuple's data order is the same as the given fields/properties order).

Let's take an example to make things clearer :

 // Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class)
 // they can be public field or properties, both can be extracted.
 List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>();
 
 fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA));
 fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF));
 fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT));
 fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF));
 fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN);
 fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN));
 
 // let's verify 'name' and 'age' of some TolkienCharacter in fellowshipOfTheRing :
 
 assertThat(fellowshipOfTheRing).extracting("name", "age")
                                .contains(tuple("Boromir", 37),
                                          tuple("Sam", 38),
                                          tuple("Legolas", 1000));
 
 
 // extract 'name', 'age' and Race name values.
 
 assertThat(fellowshipOfTheRing).extracting("name", "age", "race.name")
                                .contains(tuple("Boromir", 37, "Man"),
                                          tuple("Sam", 38, "Hobbit"),
                                          tuple("Legolas", 1000, "Elf"));
 
A property with the given name is looked for first, if it does'nt exist then a field with the given name is looked for, if no field accessible (ie. does not exist or is not public) an IntrospectionError is thrown.

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.

Parameters:
propertiesOrFields - the properties/fields to extract from the initial Iterable 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 (or field exists but is not public) in one of the initial Iterable's element.

extracting

public <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. The returned iterable becomes a new object under test.

It allows to test values from the elements in more safe way than by using extracting(String), as it doesn't utilize introspection.

Let's take a look an example

 List<
 
 // 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.

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

flatExtracting

public <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. The returned iterable becomes a new object under test.

It allows testing the results of extracting values that are represented by Iterables.

For example:

 List<CartoonCharacter> cartoonCharacters = newArrayList();
 
 CartoonCharacter bart = new CartoonCharacter("Bart Simpson");
 CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson");
 CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson");
 
 CartoonCharacter homer = new CartoonCharacter("Homer Simpson");
 homer.getChildren().add(bart);
 homer.getChildren().add(lisa);
 homer.getChildren().add(maggie);
 
 CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone");
 CartoonCharacter fred = new CartoonCharacter("Fred Flintstone");
 fred.getChildren().add(pebbles);
 
 Extractor<CartoonCharacter, List<CartoonCharacter>> childrenOf = new Extractor<CartoonChildren, List<CartoonChildren>>() {
    @Override
    public List<CartoonChildren> extract(CartoonCharacter input) {
        return input.getChildren();
    }
 }
 
 assertThat(Lists.newArrayList(homer, fred)).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.

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

containsExactlyElementsOf

public S containsExactlyElementsOf(Iterable<? extends T> iterable)
Same as 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));
 

Parameters:
iterable - the given Iterable we will get elements from.

containsOnlyElementsOf

public S containsOnlyElementsOf(Iterable<? extends T> iterable)
Same semantic as containsOnly(Object[]) : verifies that actual contains all the elements of the given iterable and nothing else, in any order.

Example :

 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));
 

Parameters:
iterable - the given Iterable we will get elements from.

hasSameElementsAs

public S hasSameElementsAs(Iterable<? extends T> iterable)
Same semantic as containsOnlyElementsOf(Iterable) : verifies that actual contains all the elements of the given iterable and nothing else, in any order.
 Example:
 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));
 

Parameters:
values - the values to verify against
Returns:
this assertion object
Throws:
AssertionError - if the actual group is null
NullPointerException - if the given Iterable is null
AssertionError - if the actual Iterable does not have the same elements, in any order, as the given Iterable

usingFieldByFieldElementComparator

public S usingFieldByFieldElementComparator()
Use field by field comparison (including inherited fields) instead of relying on actual type A equals method to compare group elements for incoming assertion checks.

This can be handy if equals method of the objects to compare does not suit you.

Note that only accessible fields values are compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.
Moreover comparison is not recursive, if one of the field is an Object, it will be compared to the other field 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 overriden 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);

 

Returns:
this assertion object.

usingElementComparatorOnFields

public S usingElementComparatorOnFields(String... fields)
Use field by field comparison on the given fields only (fields can be inherited fields) instead of relying on actual type A equals method to compare group elements for incoming assertion checks.

This can be handy if equals method of the objects to compare does not suit you.

Note that only accessible fields values are compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.
Moreover comparison is not recursive, if one of the field is an Object, it will be compared to the other field 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

 

Returns:
this assertion object.

usingComparisonStrategy

protected S usingComparisonStrategy(ComparisonStrategy comparisonStrategy)

usingElementComparatorIgnoringFields

public S usingElementComparatorIgnoringFields(String... fields)
Use field by field comparison on all fields except the given ones (fields can be inherited fields) instead of relying on actual type A equals method to compare group elements for incoming assertion checks.

This can be handy if equals method of the objects to compare does not suit you.

Note that only accessible fields values are compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.
Moreover comparison is not recursive, if one of the field is an Object, it will be compared to the other field 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

 

Returns:
this assertion object.

inHexadecimal

public S inHexadecimal()
Enable hexadecimal representation of Iterable elements instead of standard representation in error messages.

It can be useful to better understand what the error was with a more meaningful error message.

Example

 final List<Byte> bytes = newArrayList((byte) 0x10, (byte) 0x20);
 
With standard error message:
 assertThat(bytes).contains((byte)0x30);
 
 Expecting:
  <[16, 32]>
 to contain:
  <[48]>
 but could not find:
  <[48]>
 
With Hexadecimal error message:
 assertThat(bytes).inHexadecimal().contains((byte)0x30);
 
 Expecting:
  <[0x10, 0x20]>
 to contain:
  <[0x30]>
 but could not find:
  <[0x30]>
 

Overrides:
inHexadecimal in class AbstractAssert<S extends AbstractIterableAssert<S,A,T>,A extends Iterable<? extends T>>
Returns:
this assertion object.

inBinary

public S inBinary()
Enable binary representation of Iterable elements instead of standard representation in error messages.

Example:

 final List<Byte> bytes = newArrayList((byte) 0x10, (byte) 0x20);
 
With standard error message:
 assertThat(bytes).contains((byte)0x30);
 
 Expecting:
  <[16, 32]>
 to contain:
  <[48]>
 but could not find:
  <[48]>
 
With binary error message:
 assertThat(bytes).inBinary().contains((byte)0x30);
 
 Expecting:
  <[0b00010000, 0b00100000]>
 to contain:
  <[0b00110000]>
 but could not find:
  <[0b00110000]>
 

Overrides:
inBinary in class AbstractAssert<S extends AbstractIterableAssert<S,A,T>,A extends Iterable<? extends T>>
Returns:
this assertion object.


Copyright © 2013–2015 AssertJ. All rights reserved.