Class AbstractIterableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
- java.lang.Object
-
- org.assertj.core.api.AbstractAssert<SELF,ACTUAL>
-
- org.assertj.core.api.AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>
-
- Type Parameters:
SELF- the "self" type of this assertion class. Please read "Emulating 'self types' using Java Generics to simplify fluent API implementation" for more details.ACTUAL- the type of the "actual" value.ELEMENT- the type of elements of the "actual" value.ELEMENT_ASSERT- used for navigational assertions to return the right assert type.
- All Implemented Interfaces:
Assert<SELF,ACTUAL>,Descriptable<SELF>,EnumerableAssert<SELF,ELEMENT>,ExtensionPoints<SELF,ACTUAL>,ObjectEnumerableAssert<SELF,ELEMENT>
- Direct Known Subclasses:
AbstractListAssert,ClassBasedNavigableIterableAssert,FactoryBasedNavigableIterableAssert
public abstract class AbstractIterableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> extends AbstractAssert<SELF,ACTUAL> implements ObjectEnumerableAssert<SELF,ELEMENT>
Base class for implementations ofwhose actual value type isObjectEnumerableAssert.Collection- Author:
- Yvonne Wang, Alex Ruiz, Mathieu Baechler, Joel Costigliola, Maciej Jaskowski, Nicolas François, Mikhail Mazursky, Mateusz Haligowski, Lovro Pandzic, Marko Bekhta
-
-
Field Summary
Fields Modifier and Type Field Description private static StringASSERTprivate TypeComparatorscomparatorsByTypeprivate Map<String,Comparator<?>>comparatorsForElementPropertyOrFieldNamesprivate TypeComparatorscomparatorsForElementPropertyOrFieldTypesprotected Iterablesiterables-
Fields inherited from class org.assertj.core.api.AbstractAssert
actual, assertionErrorCreator, conditions, info, myself, objects, throwUnsupportedExceptionOnEquals
-
-
Constructor Summary
Constructors Constructor Description AbstractIterableAssert(ACTUAL actual, Class<?> selfType)
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Modifier and Type Method Description SELFallMatch(Predicate<? super ELEMENT> predicate)Verifies that all the elements of actual match the givenPredicate.SELFallMatch(Predicate<? super ELEMENT> predicate, String predicateDescription)Verifies that all the elements of actual match the givenPredicate.SELFallSatisfy(Consumer<? super ELEMENT> requirements)Verifies that all the elements satisfy given requirements expressed as aConsumer.SELFanyMatch(Predicate<? super ELEMENT> predicate)Verifies whether any elements match the providedPredicate.SELFanySatisfy(Consumer<? super ELEMENT> requirements)Verifies that at least one element satisfies the given requirements expressed as aConsumer.SELFare(Condition<? super ELEMENT> condition)Verifies that each element value satisfies the given condition.SELFareAtLeast(int times, Condition<? super ELEMENT> condition)Verifies that there are at least n elements in the actual group satisfying the given condition.SELFareAtLeastOne(Condition<? super ELEMENT> condition)Verifies that there is at least one element in the actual group satisfying the given condition.SELFareAtMost(int times, Condition<? super ELEMENT> condition)Verifies that there are at most n elements in the actual group satisfying the given condition.SELFareExactly(int times, Condition<? super ELEMENT> condition)Verifies that there are exactly n elements in the actual group satisfying the given condition.SELFareNot(Condition<? super ELEMENT> condition)Verifies that each element value does not satisfy the given condition.SELFas(String description, Object... args)Sets the description of the assertion that is going to be called after.SELFas(Description description)Sets the description of the assertion that is going to be called after.SELFcontains(ELEMENT... values)Verifies that the actual group contains the given values, in any order.SELFcontainsAll(Iterable<? extends ELEMENT> iterable)Verifies that the actual group contains all the elements of givenIterable, in any order.SELFcontainsAnyElementsOf(Iterable<? extends ELEMENT> iterable)SELFcontainsAnyOf(ELEMENT... values)Verifies that the actualIterablecontains at least one of the given values.SELFcontainsExactly(ELEMENT... values)Verifies that the actual group contains exactly the given values and nothing else, in order.
This assertion should only be used with groups that have a consistent iteration order (i.e.SELFcontainsExactlyElementsOf(Iterable<? extends ELEMENT> iterable)Same asObjectEnumerableAssert.containsExactly(Object...)but handle theIterableto array conversion : verifies that actual contains exactly the elements of the given iterable and nothing else in the same order.SELFcontainsExactlyInAnyOrder(ELEMENT... values)Verifies that the actual group contains exactly the given values and nothing else, in any order.SELFcontainsExactlyInAnyOrderElementsOf(Iterable<? extends ELEMENT> values)Verifies that the actual group contains exactly the given values and nothing else, in any order.SELFcontainsNull()Verifies that the actual group contains at least a null element.SELFcontainsOnly(ELEMENT... values)Verifies that the actual group contains only the given values and nothing else, in any order and ignoring duplicates (i.e.SELFcontainsOnlyElementsOf(Iterable<? extends ELEMENT> iterable)Same semantic asObjectEnumerableAssert.containsOnly(Object[]): verifies that actual contains all the elements of the given iterable and nothing else, in any order and ignoring duplicates (i.e.SELFcontainsOnlyNulls()Verifies that the actual group contains only null elements and nothing else.SELFcontainsOnlyOnce(ELEMENT... values)Verifies that the actual group contains the given values only once.SELFcontainsSequence(ELEMENT... sequence)Verifies that the actual group contains the given sequence in the correct order and without extra values between the sequence values.SELFcontainsSequence(Iterable<? extends ELEMENT> sequence)Verifies that the actual group contains the given sequence in the correct order and without extra values between the sequence values.SELFcontainsSubsequence(ELEMENT... subsequence)Verifies that the actual group contains the given subsequence in the correct order (possibly with other values between them).SELFcontainsSubsequence(Iterable<? extends ELEMENT> subsequence)Verifies that the actual group contains the given subsequence in the correct order (possibly with other values between them).SELFdescribedAs(String description, Object... args)Sets the description of the assertion that is going to be called after.SELFdescribedAs(Description description)Sets the description of the assertion that is going to be called after.SELFdoesNotContain(ELEMENT... values)Verifies that the actual group does not contain the given values.SELFdoesNotContainAnyElementsOf(Iterable<? extends ELEMENT> iterable)Verifies that actual does not contain any elements of the givenIterable(i.e.SELFdoesNotContainNull()Verifies that the actual group does not contain null elements.SELFdoesNotContainSequence(ELEMENT... sequence)Verifies that the actual group does not contain the given sequence, a sequence is defined by an ordered group of values without extra values between them.SELFdoesNotContainSequence(Iterable<? extends ELEMENT> sequence)Verifies that the actual group does not contain the given sequence, a sequence is defined by an ordered group of values without extra values between them.SELFdoesNotContainSubsequence(ELEMENT... subsequence)Verifies that the actual group does not contain the given subsequence, a subsequence is defined by an ordered group of values with possibly extra values between them.SELFdoesNotContainSubsequence(Iterable<? extends ELEMENT> subsequence)Verifies that the actual group does not contain the given subsequence, a subsequence is defined by an ordered group of values with possibly extra values between them.SELFdoesNotHave(Condition<? super ACTUAL> condition)Verifies that the actual value does not satisfy the given condition.SELFdoesNotHaveAnyElementsOfTypes(Class<?>... unexpectedTypes)Verifies that all elements in the actualIterabledo not have the specified types (including subclasses).SELFdoesNotHaveDuplicates()Verifies that the actual group does not contain duplicates.SELFdoesNotHaveSameClassAs(Object other)Verifies that the actual value does not have the same class as the given object.private <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>>doFlatExtracting(Function<? super ELEMENT,? extends Collection<V>> extractor)SELFdoNotHave(Condition<? super ELEMENT> condition)Verifies that all elements do not satisfy the given condition.ELEMENT_ASSERTelement(int index)Navigate and allow to perform assertions on the chosen element of theIterableunder test.SELFendsWith(ELEMENT[] sequence)Verifies that the actual group ends with the given sequence of objects, without any other objects between them.SELFendsWith(ELEMENT first, ELEMENT... rest)Verifies that the actual group ends with the given sequence of objects, without any other objects between them.AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>>extracting(String propertyOrField)Extract the values of the given field or property from the Iterable's elements under test into a new Iterable, this new Iterable becoming the Iterable under test.AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>>extracting(String... propertiesOrFields)Extract the values of the given fields/properties from the Iterable's elements under test into a new Iterable composed of Tuples (a simple data structure), this new Iterable becoming the Iterable under test.<P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>>extracting(String propertyOrField, Class<P> extractingType)Extract the values of given field or property from the Iterable's elements under test into a new Iterable, this new Iterable becoming the Iterable under test.AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>>extracting(Function<? super ELEMENT,?>... extractors)<V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>>extracting(Function<? super ELEMENT,V> extractor)Extract the values from Iterable's elements under test by applying an extracting function on them.<V,EXCEPTION extends Exception>
AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>>extracting(ThrowingExtractor<? super ELEMENT,V,EXCEPTION> extractor)Extract the values from Iterable's elements under test by applying an extracting function (which might throw an exception) on them.AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>>extractingResultOf(String method)Extract the result of given method invocation on the Iterable's elements under test into a new Iterable, this new Iterable becoming the Iterable under test.<P> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>>extractingResultOf(String method, Class<P> extractedType)Extract the result of given method invocation on the Iterable's elements under test into a new list of the given class, this new List becoming the object under test.SELFfilteredOn(String propertyOrFieldName, Object expectedValue)Filter the iterable under test keeping only elements having a property or field equal toexpectedValue, the property/field is specified bypropertyOrFieldNameparameter.SELFfilteredOn(String propertyOrFieldName, FilterOperator<?> filterOperator)Filter the iterable under test keeping only elements having a property or field matching the filter expressed with theFilterOperator, the property/field is specified bypropertyOrFieldNameparameter.SELFfilteredOn(Predicate<? super ELEMENT> predicate)Filter the iterable under test keeping only elements matching the givenPredicate.SELFfilteredOn(Condition<? super ELEMENT> condition)Filter the iterable under test keeping only elements matching the givenCondition.SELFfilteredOnAssertions(Consumer<? super ELEMENT> elementAssertions)Filter the iterable under test keeping only elements matching the given assertions specified with aConsumer.SELFfilteredOnNull(String propertyOrFieldName)Filter the iterable under test keeping only elements whose property or field specified bypropertyOrFieldNameis null.ELEMENT_ASSERTfirst()Navigate and allow to perform assertions on the first element of theIterableunder test.AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>>flatExtracting(String fieldOrPropertyName)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.AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>>flatExtracting(String... fieldOrPropertyNames)Extract the given property/field values from eachIterable's element and flatten the extracted values in a list that is used as the new object under test.AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>>flatExtracting(Function<? super ELEMENT,?>... extractors)Extract multiple values from eachIterable's element according to the givenFunctions and concatenate/flatten the extracted values in a list that is used as the new object under test.<V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>>flatExtracting(Function<? super ELEMENT,? 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.<EXCEPTION extends Exception>
AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>>flatExtracting(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>... extractors)Extract multiple values from eachIterable's element according to the givenThrowingExtractors and concatenate/flatten the extracted values in a list that is used as the new object under test.<V,EXCEPTION extends Exception>
AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>>flatExtracting(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION> extractor)Extract the Iterable values from Iterable's elements under test by applying an Iterable extracting function (which might throw a checked exception) on them and concatenating the result lists.protected TypeComparatorsgetComparatorsByType()protected TypeComparatorsgetComparatorsForElementPropertyOrFieldTypes()SELFhas(Condition<? super ACTUAL> condition)Verifies that the actual value satisfies the given condition.SELFhasAtLeastOneElementOfType(Class<?> expectedType)Verifies that at least one element in the actualIterablehas the specified type (matching includes subclasses of the given type).SELFhasOnlyElementsOfType(Class<?> expectedType)Verifies that all elements in the actualIterablehave the specified type (matching includes subclasses of the given type).SELFhasOnlyElementsOfTypes(Class<?>... types)Verifies that all elements of the actual group are instances of the given types.SELFhasOnlyOneElementSatisfying(Consumer<? super ELEMENT> elementAssertions)Verifies that the unique element of theIterablesatifies the given assertions expressed as aConsumer, if it does not, only the first error is reported, useSoftAssertionsto get all the errors.SELFhasSameClassAs(Object other)Verifies that the actual value has the same class as the given object.SELFhasSameElementsAs(Iterable<? extends ELEMENT> iterable)An alias ofObjectEnumerableAssert.containsOnlyElementsOf(Iterable): verifies that actual contains all the elements of the given iterable and nothing else, in any order.SELFhasSameSizeAs(Iterable<?> other)Verifies that the actual group has the same size as givenIterable.SELFhasSameSizeAs(Object other)Verifies that the actual group has the same size as given array.SELFhasSize(int expected)Verifies that the number of values in the actual group is equal to the given one.SELFhasSizeBetween(int lowerBoundary, int higherBoundary)Verifies that the number of values in the actual iterable is between the given boundaries (inclusive).SELFhasSizeGreaterThan(int boundary)Verifies that the number of values in the actual iterable is greater than the given boundary.SELFhasSizeGreaterThanOrEqualTo(int boundary)Verifies that the number of values in the actual iterable is greater than or equal to the given boundary.SELFhasSizeLessThan(int boundary)Verifies that the number of values in the actual iterable is less than the given boundary.SELFhasSizeLessThanOrEqualTo(int boundary)Verifies that the number of values in the actual iterable is less than or equal to the given boundary.SELFhasToString(String expectedToString)Verifies that actualactual.toString()is equal to the givenString.SELFhave(Condition<? super ELEMENT> condition)Verifies that all elements satisfy the given condition.SELFhaveAtLeast(int times, Condition<? super ELEMENT> condition)Verifies that there are at least n elements in the actual group satisfying the given condition.SELFhaveAtLeastOne(Condition<? super ELEMENT> condition)Verifies that there is at least one element in the actual group satisfying the given condition.SELFhaveAtMost(int times, Condition<? super ELEMENT> condition)Verifies that there are at most n elements in the actual group satisfying the given condition.SELFhaveExactly(int times, Condition<? super ELEMENT> condition)Verifies that there are exactly n elements in the actual group satisfying the given condition.SELFinBinary()Enable binary representation of Iterable elements instead of standard representation in error messages.SELFinHexadecimal()Enable hexadecimal representation of Iterable elements instead of standard representation in error messages.SELFis(Condition<? super ACTUAL> condition)Verifies that the actual value satisfies the given condition.voidisEmpty()Verifies that the actual group of values is empty.SELFisEqualTo(Object expected)Verifies that the actual value is equal to the given one.SELFisExactlyInstanceOf(Class<?> type)Verifies that the actual value is exactly an instance of the given type.SELFisIn(Iterable<?> values)Verifies that the actual value is present in the given values.SELFisIn(Object... values)Verifies that the actual value is present in the given array of values.SELFisInstanceOf(Class<?> type)Verifies that the actual value is an instance of the given type.SELFisInstanceOfAny(Class<?>... types)Verifies that the actual value is an instance of any of the given types.SELFisNot(Condition<? super ACTUAL> condition)Verifies that the actual value does not satisfy the given condition.SELFisNotEmpty()Verifies that the actual group of values is not empty.SELFisNotEqualTo(Object other)Verifies that the actual value is not equal to the given one.SELFisNotExactlyInstanceOf(Class<?> type)Verifies that the actual value is not exactly an instance of given type.SELFisNotIn(Iterable<?> values)Verifies that the actual value is not present in the given values.SELFisNotIn(Object... values)Verifies that the actual value is not present in the given array of values.SELFisNotInstanceOf(Class<?> type)Verifies that the actual value is not an instance of the given type.SELFisNotInstanceOfAny(Class<?>... types)Verifies that the actual value is not an instance of any of the given types.SELFisNotNull()Verifies that the actual value is notnull.SELFisNotOfAnyClassIn(Class<?>... types)Verifies that the actual value type is not in given types.SELFisNotSameAs(Object other)Verifies that the actual value is not the same as the given one, ie using == comparison.voidisNullOrEmpty()Verifies that the actual group of values isnullor empty.SELFisOfAnyClassIn(Class<?>... types)Verifies that the actual value type is in given types.SELFisSameAs(Object expected)Verifies that the actual value is the same as the given one, ie using == comparison.SELFisSubsetOf(ELEMENT... values)Verifies that all the elements of actual are present in the given values.SELFisSubsetOf(Iterable<? extends ELEMENT> values)Verifies that all the elements of actual are present in the givenIterable.ELEMENT_ASSERTlast()Navigate and allow to perform assertions on the last element of theIterableunder test.private ELEMENTlastElement()protected StringnavigationDescription(String propertyName)protected abstract SELFnewAbstractIterableAssert(Iterable<? extends ELEMENT> iterable)private <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>>newListAssertInstanceForMethodsChangingElementType(List<V> values)SELFnoneMatch(Predicate<? super ELEMENT> predicate)Verifies that no elements match the givenPredicate.SELFnoneSatisfy(Consumer<? super ELEMENT> restrictions)Verifies that no elements satisfy the given restrictions expressed as aConsumer.SELFoverridingErrorMessage(String newErrorMessage, Object... args)Overrides AssertJ default error message by the given one.private static StringremoveAssert(String text)AbstractIterableSizeAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>size()Returns anAssertobject that allows performing assertions on the size of theIterableunder test.SELFstartsWith(ELEMENT... sequence)Verifies that the actual group starts with the given sequence of objects, without any other objects between them.protected abstract ELEMENT_ASSERTtoAssert(ELEMENT value, String description)SELFusingComparator(Comparator<? super ACTUAL> customComparator)Use the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.SELFusingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription)Use the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.<T> SELFusingComparatorForElementFieldsWithNames(Comparator<T> comparator, String... elementPropertyOrFieldNames)Allows to set a comparator to compare properties or fields of elements with the given names.<T> SELFusingComparatorForElementFieldsWithType(Comparator<T> comparator, Class<T> type)Allows to set a specific comparator to compare properties or fields of elements with the given type.<T> SELFusingComparatorForType(Comparator<T> comparator, Class<T> type)Allows to set a specific comparator for the given type of elements or their fields.protected SELFusingComparisonStrategy(ComparisonStrategy comparisonStrategy)SELFusingDefaultComparator()Revert to standard comparison for the incoming assertion checks.SELFusingDefaultElementComparator()Revert to standard comparison for incoming assertion group element checks.SELFusingElementComparator(Comparator<? super ELEMENT> elementComparator)Use given custom comparator instead of relying on actual type Aequalsmethod to compare group elements for incoming assertion checks.SELFusingElementComparatorIgnoringFields(String... fields)Use field/property by field/property comparison on all fields/properties except the given ones (including inherited fields/properties) instead of relying on actual type Aequalsmethod to compare group elements for incoming assertion checks.SELFusingElementComparatorOnFields(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 Aequalsmethod to compare group elements for incoming assertion checks.private SELFusingExtendedByTypesElementComparator(Comparator<Object> elementComparator)SELFusingFieldByFieldElementComparator()Use field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type Aequalsmethod to compare group elements for incoming assertion checks.SELFusingRecursiveFieldByFieldElementComparator()Use a recursive field/property by field/property comparison (including inherited fields/properties) instead of relying on actual typeequalsmethod to compare group elements for incoming assertion checks.(package private) SELFwithAssertionState(AbstractAssert assertInstance)(package private) SELFwithComparatorsForElementPropertyOrFieldNames(Map<String,Comparator<?>> comparatorsForElementPropertyOrFieldNames)(package private) SELFwithComparatorsForElementPropertyOrFieldTypes(TypeComparators comparatorsForElementPropertyOrFieldTypes)SELFwithFailMessage(String newErrorMessage, Object... args)Alternative method forAbstractAssert.overridingErrorMessage(java.lang.String, java.lang.Object...)(package private) SELFwithIterables(Iterables iterables)SELFwithThreadDumpOnError()In case of an assertion error, a thread dump will be printed toSystem.err.(package private) SELFwithTypeComparators(TypeComparators comparatorsByType)<OTHER_ELEMENT>
SELFzipSatisfy(Iterable<OTHER_ELEMENT> other, BiConsumer<? super ELEMENT,OTHER_ELEMENT> zipRequirements)Verifies that the zipped pairs of actual and other elements, i.e: (actual 1st element, other 1st element), (actual 2nd element, other 2nd element), ...-
Methods inherited from class org.assertj.core.api.AbstractAssert
asInstanceOf, asList, asString, descriptionText, equals, failWithMessage, getWritableAssertionInfo, hashCode, hasSameHashCodeAs, isInstanceOfSatisfying, isNull, matches, matches, newListAssertInstance, satisfies, satisfies, satisfiesAnyOf, satisfiesAnyOf, setCustomRepresentation, throwAssertionError, withRepresentation
-
-
-
-
Field Detail
-
ASSERT
private static final String ASSERT
- See Also:
- Constant Field Values
-
comparatorsByType
private TypeComparators comparatorsByType
-
comparatorsForElementPropertyOrFieldNames
private Map<String,Comparator<?>> comparatorsForElementPropertyOrFieldNames
-
comparatorsForElementPropertyOrFieldTypes
private TypeComparators comparatorsForElementPropertyOrFieldTypes
-
iterables
protected Iterables iterables
-
-
Method Detail
-
isNullOrEmpty
public void isNullOrEmpty()
Verifies that the actual group of values isnullor empty.Example:
// assertions will pass List<String> strings = new ArrayList<>(); assertThat(strings).isNullOrEmpty(); assertThat(new int[] { }).isNullOrEmpty(); // assertions will fail assertThat(new String[] { "a", "b"}).isNullOrEmpty(); assertThat(Arrays.asList(1, 2, 3)).isNullOrEmpty();- Specified by:
isNullOrEmptyin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>
-
isEmpty
public void isEmpty()
Verifies that the actual group of values is empty.Example:
// assertions will pass assertThat(new ArrayList()).isEmpty(); assertThat(new int[] { }).isEmpty(); // assertions will fail assertThat(new String[] { "a", "b" }).isEmpty(); assertThat(Arrays.asList(1, 2, 3)).isEmpty();- Specified by:
isEmptyin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>
-
isNotEmpty
public SELF isNotEmpty()
Verifies that the actual group of values is not empty.Example:
// assertions will pass assertThat(new String[] { "a", "b" }).isNotEmpty(); assertThat(Arrays.asList(1, 2, 3)).isNotEmpty(); // assertions will fail assertThat(new ArrayList()).isNotEmpty(); assertThat(new int[] { }).isNotEmpty();- Specified by:
isNotEmptyin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
hasSize
public SELF hasSize(int expected)
Verifies that the number of values in the actual group is equal to the given one.Example:
// assertions will pass assertThat(new String[] { "a", "b" }).hasSize(2); assertThat(Arrays.asList(1, 2, 3)).hasSize(3); // assertions will fail assertThat(new ArrayList()).hasSize(1); assertThat(new int[] { 1, 2, 3 }).hasSize(2);- Specified by:
hasSizein interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
expected- the expected number of values in the actual group.- Returns:
thisassertion object.
-
hasSizeGreaterThan
public SELF hasSizeGreaterThan(int boundary)
Verifies that the number of values in the actual iterable is greater than the given boundary.Example:
// assertion will pass assertThat(Arrays.asList(1, 2, 3)).hasSizeGreaterThan(2); // assertion will fail assertThat(Arrays.asList(1, 2, 3)).hasSizeGreaterThan(3);- Specified by:
hasSizeGreaterThanin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
boundary- the given value to compare the actual size to.- Returns:
thisassertion object.- Throws:
AssertionError- if the number of values of the actual iterable is not greater than the boundary.- Since:
- 3.12.0
-
hasSizeGreaterThanOrEqualTo
public SELF hasSizeGreaterThanOrEqualTo(int boundary)
Verifies that the number of values in the actual iterable is greater than or equal to the given boundary.Example:
// assertions will pass assertThat(Arrays.asList(1, 2, 3)).hasSizeGreaterThanOrEqualTo(1) .hasSizeGreaterThanOrEqualTo(3); // assertion will fail assertThat(Arrays.asList(1, 2, 3)).hasSizeGreaterThanOrEqualTo(4);- Specified by:
hasSizeGreaterThanOrEqualToin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
boundary- the given value to compare the actual size to.- Returns:
thisassertion object.- Throws:
AssertionError- if the number of values of the actual iterable is not greater than or equal to the boundary.- Since:
- 3.12.0
-
hasSizeLessThan
public SELF hasSizeLessThan(int boundary)
Verifies that the number of values in the actual iterable is less than the given boundary.Example:
// assertion will pass assertThat(Arrays.asList(1, 2, 3)).hasSizeLessThan(4); // assertion will fail assertThat(Arrays.asList(1, 2, 3)).hasSizeLessThan(3);- Specified by:
hasSizeLessThanin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
boundary- the given value to compare the actual size to.- Returns:
thisassertion object.- Throws:
AssertionError- if the number of values of the actual iterable is not less than the boundary.- Since:
- 3.12.0
-
hasSizeLessThanOrEqualTo
public SELF hasSizeLessThanOrEqualTo(int boundary)
Verifies that the number of values in the actual iterable is less than or equal to the given boundary.Example:
// assertions will pass assertThat(Arrays.asList(1, 2, 3)).hasSizeLessThanOrEqualTo(5) .hasSizeLessThanOrEqualTo(3); // assertion will fail assertThat(Arrays.asList(1, 2, 3)).hasSizeLessThanOrEqualTo(2);- Specified by:
hasSizeLessThanOrEqualToin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
boundary- the given value to compare the actual size to.- Returns:
thisassertion object.- Throws:
AssertionError- if the number of values of the actual iterable is not less than or equal to the boundary.- Since:
- 3.12.0
-
hasSizeBetween
public SELF hasSizeBetween(int lowerBoundary, int higherBoundary)
Verifies that the number of values in the actual iterable is between the given boundaries (inclusive).Example:
// assertions will pass assertThat(Arrays.asList(1, 2, 3)).hasSizeBetween(2, 3) .hasSizeBetween(3, 4) .hasSizeBetween(3, 3); // assertion will fail assertThat(Arrays.asList(1, 2, 3)).hasSizeBetween(4, 6);- Specified by:
hasSizeBetweenin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
lowerBoundary- the lower boundary compared to which actual size should be greater than or equal to.higherBoundary- the higher boundary compared to which actual size should be less than or equal to.- Returns:
thisassertion object.- Throws:
AssertionError- if the number of values of the actual iterable is not between the boundaries.- Since:
- 3.12.0
-
hasOnlyOneElementSatisfying
public SELF hasOnlyOneElementSatisfying(Consumer<? super ELEMENT> elementAssertions)
Verifies that the unique element of theIterablesatifies the given assertions expressed as aConsumer, if it does not, only the first error is reported, useSoftAssertionsto get all the errors.Example:
List<Jedi> jedis = asList(new Jedi("Yoda", "red")); // assertions will pass assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("Y")); assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> { assertThat(yoda.getName()).isEqualTo("Yoda"); assertThat(yoda.getLightSaberColor()).isEqualTo("red"); }); // assertions will fail assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("Vad")); // fail as one the assertions is not satisfied assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> { assertThat(yoda.getName()).isEqualTo("Yoda"); assertThat(yoda.getLightSaberColor()).isEqualTo("purple"); }); // fail but only report the first error assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> { assertThat(yoda.getName()).isEqualTo("Luke"); assertThat(yoda.getLightSaberColor()).isEqualTo("green"); }); // fail and reports the errors thanks to Soft assertions assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> { SoftAssertions softly = new SoftAssertions(); softly.assertThat(yoda.getName()).isEqualTo("Luke"); softly.assertThat(yoda.getLightSaberColor()).isEqualTo("green"); softly.assertAll(); }); // even if the assertion is correct, there are too many jedis ! jedis.add(new Jedi("Luke", "green")); assertThat(jedis).hasOnlyOneElementSatisfying(yoda -> assertThat(yoda.getName()).startsWith("Yo"));- Specified by:
hasOnlyOneElementSatisfyingin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
elementAssertions- the assertions to perform on the unique element.- Returns:
thisassertion object.- Throws:
AssertionError- if theIterabledoes not have a unique element.AssertionError- if theIterable's unique element does not satifies the given assertions.- Since:
- 3.5.0
-
hasSameSizeAs
public SELF 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[]).
Example:int[] oneTwoThree = {1, 2, 3}; Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass assertThat(elvesRings).hasSameSizeAs(oneTwoThree); // assertions will fail assertThat(elvesRings).hasSameSizeAs(new int[] { 1, 2}); assertThat(elvesRings).hasSameSizeAs(new int[] { 1, 2, 3, 4});- Specified by:
hasSameSizeAsin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
other- the array to compare size with actual group.- Returns:
thisassertion object.
-
hasSameSizeAs
public SELF hasSameSizeAs(Iterable<?> other)
Verifies that the actual group has the same size as givenIterable.Example:
Iterable<String> abc = newArrayList("a", "b", "c"); Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass assertThat(elvesRings).hasSameSizeAs(abc); // assertions will fail assertThat(elvesRings).hasSameSizeAs(Arrays.asList(1, 2)); assertThat(elvesRings).hasSameSizeAs(Arrays.asList(1, 2, 3, 4));- Specified by:
hasSameSizeAsin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
other- theIterableto compare size with actual group.- Returns:
thisassertion object.
-
contains
public SELF contains(ELEMENT... values)
Verifies that the actual group contains the given values, in any order.Example:
Iterable<String> abc = newArrayList("a", "b", "c"); // assertions will pass assertThat(abc).contains("b", "a"); assertThat(abc).contains("b", "a", "b"); // assertion will fail assertThat(abc).contains("d");If you want to specify the elements to check with an
Iterable, usecontainsAll(Iterable)instead.- Specified by:
containsin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given values.- Returns:
thisassertion object.
-
containsOnly
public SELF containsOnly(ELEMENT... values)
Verifies that the actual group contains only the given values and nothing else, in any order and ignoring duplicates (i.e. once a value is found, its duplicates are also considered found).If you need to check exactly the elements and their duplicates use:
containsExactly(Object...)if the order does mattercontainsExactlyInAnyOrder(Object...)if the order does not matter
Example:
Iterable<String> abc = newArrayList("a", "b", "c"); // assertions will pass as order does not matter assertThat(abc).containsOnly("c", "b", "a"); // duplicates are ignored assertThat(abc).containsOnly("a", "a", "b", "c", "c"); // ... on both actual and expected values assertThat(asList("a", "a", "b")).containsOnly("a", "b") .containsOnly("a", "a", "b", "b"); // assertion will fail because "c" is missing in the given values assertThat(abc).containsOnly("a", "b"); // assertion will fail because "d" is missing in abc (use isSubsetOf if you want this assertion to pass) assertThat(abc).containsOnly("a", "b", "c", "d");If you need to check that actual is a subset of the given values, use
ObjectEnumerableAssert.isSubsetOf(Object...).If you want to specify the elements to check with an
Iterable, usecontainsOnlyElementsOf(Iterable)instead.- Specified by:
containsOnlyin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given values.- Returns:
thisassertion object.
-
containsOnlyOnce
public SELF containsOnlyOnce(ELEMENT... values)
Verifies that the actual group contains the given values only once.Examples :
// lists are used in the examples but it would also work with arrays // assertions will pass assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("winter"); assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("coming", "winter"); // assertions will fail assertThat(newArrayList("winter", "is", "coming")).containsOnlyOnce("Lannister"); assertThat(newArrayList("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark"); assertThat(newArrayList("Arya", "Stark", "daughter", "of", "Ned", "Stark")).containsOnlyOnce("Stark", "Lannister", "Arya");- Specified by:
containsOnlyOncein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given values.- Returns:
thisassertion object.
-
containsOnlyNulls
public SELF containsOnlyNulls()
Verifies that the actual group contains only null elements and nothing else.Example:
// assertion will pass Iterable<String> items = Arrays.asList(null, null, null); assertThat(items).containsOnlyNulls(); // assertion will fail because items2 contains a not null element Iterable<String> items2 = Arrays.asList(null, null, "notNull"); assertThat(items2).containsOnlyNulls(); // assertion will fail since an empty iterable does not contain any elements and therefore no null ones. Iterable<String> empty = new ArrayList<>(); assertThat(empty).containsOnlyNulls();- Specified by:
containsOnlyNullsin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
containsExactly
public SELF containsExactly(ELEMENT... values)
Verifies that the actual group contains exactly the given values and nothing else, in order.
This assertion should only be used with groups that have a consistent iteration order (i.e. don't use it withHashSet, preferObjectEnumerableAssert.containsOnly(Object...)in that case).Example:
// an Iterable is used in the example but it would also work with an array Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass assertThat(elvesRings).containsExactly(vilya, nenya, narya); // assertion will fail as actual and expected order differ assertThat(elvesRings).containsExactly(nenya, vilya, narya);If you want to specify the elements to check with an
Iterable, usecontainsExactlyElementsOf(Iterable)instead.- Specified by:
containsExactlyin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given values.- Returns:
thisassertion object.
-
containsExactlyInAnyOrder
public SELF containsExactlyInAnyOrder(ELEMENT... values)
Verifies that the actual group contains exactly the given values 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, vilya); // assertion will pass assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya); // assertion will fail as vilya is contained twice in elvesRings. assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);If you want to specify the elements to check with an
Iterable, usecontainsExactlyInAnyOrderElementsOf(Iterable)instead.- Specified by:
containsExactlyInAnyOrderin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given values.- Returns:
thisassertion object.
-
containsExactlyInAnyOrderElementsOf
public SELF containsExactlyInAnyOrderElementsOf(Iterable<? extends ELEMENT> values)
Verifies that the actual group contains exactly the given values 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, vilya); Iterable<Ring> elvesRingsSomeMissing = newArrayList(vilya, nenya, narya); Iterable<Ring> elvesRingsDifferentOrder = newArrayList(nenya, narya, vilya, vilya); // assertion will pass assertThat(elvesRings).containsExactlyInAnyOrder(elvesRingsDifferentOrder); // assertion will fail as vilya is contained twice in elvesRings. assertThat(elvesRings).containsExactlyInAnyOrder(elvesRingsSomeMissing);If you want to directly specify the elements to check, use
containsExactlyInAnyOrder(Object...)instead.- Specified by:
containsExactlyInAnyOrderElementsOfin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given values.- Returns:
thisassertion object.
-
isSubsetOf
public SELF isSubsetOf(Iterable<? extends ELEMENT> values)
Verifies that all the elements of actual are present in the givenIterable.Example:
// an Iterable is used in the example but it would also work with an array List<Ring> ringsOfPower = newArrayList(oneRing, vilya, nenya, narya, dwarfRing, manRing); Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass: assertThat(elvesRings).isSubsetOf(ringsOfPower); // assertion will fail: assertThat(elvesRings).isSubsetOf(newArrayList(nenya, narya));If you want to directly specify the set of elements, use
isSubsetOf(Object...)instead.- Specified by:
isSubsetOfin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- theIterablethat should contain all actual elements.- Returns:
- this assertion object.
-
isSubsetOf
public SELF isSubsetOf(ELEMENT... values)
Verifies that all the elements of actual are present in the given values.Example:
// an Iterable is used in the example but it would also work with an array Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass: assertThat(elvesRings).isSubsetOf(vilya, nenya, narya) .isSubsetOf(vilya, nenya, narya, dwarfRing); // assertions will fail: assertThat(elvesRings).isSubsetOf(vilya, nenya); assertThat(elvesRings).isSubsetOf(vilya, nenya, dwarfRing);If you want to specify the set of elements an
Iterable, useisSubsetOf(Iterable)instead.- Specified by:
isSubsetOfin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the values that should be used for checking the elements of actual.- Returns:
- this assertion object.
-
containsSequence
public SELF containsSequence(ELEMENT... sequence)
Verifies that the actual group contains the given sequence in the correct order and without extra values between the sequence values.Use
ObjectEnumerableAssert.containsSubsequence(Object...)to allow values between the expected sequence values.Example:
// an Iterable is used in the example but it would also work with an array Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass assertThat(elvesRings).containsSequence(vilya, nenya) .containsSequence(nenya, narya); // assertions will fail, the elements order is correct but there is a value between them (nenya) assertThat(elvesRings).containsSequence(vilya, narya); assertThat(elvesRings).containsSequence(nenya, vilya);If you want to specify the sequence to check with an
Iterable, usecontainsSequence(Iterable)instead.- Specified by:
containsSequencein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
sequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
containsSequence
public SELF containsSequence(Iterable<? extends ELEMENT> sequence)
Verifies that the actual group contains the given sequence in the correct order and without extra values between the sequence values.Use
ObjectEnumerableAssert.containsSubsequence(Iterable)to allow values between the expected sequence values.Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass assertThat(elvesRings).containsSequence(newArrayList(vilya, nenya)) .containsSequence(newArrayList(nenya, narya)); // assertions will fail, the elements order is correct but there is a value between them (nenya) assertThat(elvesRings).containsSequence(newArrayList(vilya, narya)); assertThat(elvesRings).containsSequence(newArrayList(nenya, vilya));If you want to directly specify the elements of the sequence to check, use
containsSequence(Object...)instead.- Specified by:
containsSequencein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
sequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
doesNotContainSequence
public SELF doesNotContainSequence(ELEMENT... sequence)
Verifies that the actual group does not contain the given sequence, a sequence is defined by an ordered group of values without extra values between them.Use
ObjectEnumerableAssert.doesNotContainSubsequence(Object...)to also ensure the sequence does not exist with values between the expected sequence values.Example:
// an Iterable is used in the example but it would also work with an array Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass, the elements order is correct but there is a value between them (nenya) assertThat(elvesRings).doesNotContainSequence(vilya, narya) .doesNotContainSequence(nenya, vilya); // assertions will fail assertThat(elvesRings).doesNotContainSequence(vilya, nenya); assertThat(elvesRings).doesNotContainSequence(nenya, narya);If you want to specify the sequence not to find with an
Iterable, usedoesNotContainSequence(Iterable)instead.- Specified by:
doesNotContainSequencein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
sequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
doesNotContainSequence
public SELF doesNotContainSequence(Iterable<? extends ELEMENT> sequence)
Verifies that the actual group does not contain the given sequence, a sequence is defined by an ordered group of values without extra values between them.Use
ObjectEnumerableAssert.doesNotContainSubsequence(Iterable)to also ensure the sequence does not exist with values between the sequence values.Example:
// an Iterable is used in the example but it would also work with an array Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass, the elements order is correct but there is a value between them (nenya) assertThat(elvesRings).doesNotContainSequence(newArrayList(vilya, narya)) .doesNotContainSequence(newArrayList(nenya, vilya)); // assertions will fail assertThat(elvesRings).doesNotContainSequence(newArrayList(vilya, nenya)); assertThat(elvesRings).doesNotContainSequence(newArrayList(nenya, narya));If you want to directly specify the elements of the sequence not to find, use
doesNotContainSequence(Object...)instead.- Specified by:
doesNotContainSequencein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
sequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
containsSubsequence
public SELF containsSubsequence(ELEMENT... subsequence)
Verifies that the actual group contains the given subsequence in the correct order (possibly with other values between them).Example:
// an Iterable is used in the example but it would also work with an array Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass assertThat(elvesRings).containsSubsequence(vilya, nenya) .containsSubsequence(vilya, narya); // assertion will fail assertThat(elvesRings).containsSubsequence(nenya, vilya);If you want to specify the elements of the subsequence to check with an
Iterable, usecontainsSubsequence(Iterable)instead.- Specified by:
containsSubsequencein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
subsequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
containsSubsequence
public SELF containsSubsequence(Iterable<? extends ELEMENT> subsequence)
Verifies that the actual group contains the given subsequence in the correct order (possibly with other values between them).Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass assertThat(elvesRings).containsSubsequence(newArrayList(vilya, nenya)) .containsSubsequence(newArrayList(vilya, narya)); // assertion will fail assertThat(elvesRings).containsSubsequence(newArrayList(nenya, vilya));If you want to directly specify the subsequence to check, use
containsSubsequence(Object...)instead.- Specified by:
containsSubsequencein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
subsequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
doesNotContainSubsequence
public SELF doesNotContainSubsequence(ELEMENT... subsequence)
Verifies that the actual group does not contain the given subsequence, a subsequence is defined by an ordered group of values with possibly extra values between them.Example:
// an Iterable is used in the example but it would also work with an array Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass assertThat(elvesRings).doesNotContainSubsequence(nenya, vilya) .doesNotContainSubsequence(narya, vilya); // assertion will fail assertThat(elvesRings).doesNotContainSubsequence(vilya, nenya); assertThat(elvesRings).doesNotContainSubsequence(vilya, narya);If you want to specify the subsequence not to find with an
Iterable, usedoesNotContainSubsequence(Iterable)instead.- Specified by:
doesNotContainSubsequencein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
subsequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
doesNotContainSubsequence
public SELF doesNotContainSubsequence(Iterable<? extends ELEMENT> subsequence)
Verifies that the actual group does not contain the given subsequence, a subsequence is defined by an ordered group of values with possibly extra values between them.Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertions will pass assertThat(elvesRings).doesNotContainSubsequence(newArrayList(nenya, vilya)); .doesNotContainSubsequence(newArrayList(narya, vilya)); // assertion will fail assertThat(elvesRings).doesNotContainSubsequence(newArrayList(vilya, nenya)); assertThat(elvesRings).doesNotContainSubsequence(newArrayList(vilya, narya));If you want to directly specify the elements of the subsequence not to find, use
doesNotContainSubsequence(Object...)instead.- Specified by:
doesNotContainSubsequencein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
subsequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
doesNotContain
public SELF doesNotContain(ELEMENT... values)
Description copied from interface:ObjectEnumerableAssertVerifies that the actual group does not contain the given 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).doesNotContain("d") .doesNotContain("d", "e"); // assertions will fail assertThat(abc).doesNotContain("a"); assertThat(abc).doesNotContain("a", "b"); assertThat(abc).doesNotContain("c", "d");If you want to specify the elements not to find with an
Iterable, usedoesNotContainAnyElementsOf(Iterable)instead.- Specified by:
doesNotContainin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given values.- Returns:
thisassertion object.
-
doesNotContainAnyElementsOf
public SELF doesNotContainAnyElementsOf(Iterable<? extends ELEMENT> iterable)
Description copied from interface:ObjectEnumerableAssertVerifies that actual does not contain any elements of the givenIterable(i.e. none).Example:
Iterable<String> abc = newArrayList("a", "b", "c"); // assertion succeeds: assertThat(actual).doesNotContainAnyElementsOf(newArrayList("d", "e")); // assertion fails: assertThat(actual).doesNotContainAnyElementsOf(newArrayList("d", "e", "a"));If you want to directly specify the elements not to find, use
doesNotContain(Object...)instead.- Specified by:
doesNotContainAnyElementsOfin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
iterable- theIterablewhose elements must not be in the actual group.- Returns:
thisassertion object.
-
doesNotHaveDuplicates
public SELF doesNotHaveDuplicates()
Verifies that the actual group does not contain duplicates.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();- Specified by:
doesNotHaveDuplicatesin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
startsWith
public SELF startsWith(ELEMENT... sequence)
Verifies that the actual group starts with the given sequence of objects, without any other objects between them. Similar to, but it also verifies that the first element in the sequence is also first element of the actual group.ObjectEnumerableAssert.containsSequence(Object...)Example:
// an Iterable is used in the example but it would also work with an array Iterable<String> abc = newArrayList("a", "b", "c"); // assertions will pass assertThat(abc).startsWith("a") .startsWith("a", "b"); // assertion will fail assertThat(abc).startsWith("c");- Specified by:
startsWithin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
sequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
endsWith
public SELF endsWith(ELEMENT first, ELEMENT... rest)
Verifies that the actual group ends with the given sequence of objects, without any other objects between them. Similar to, but it also verifies that the last element in the sequence is also last element of the actual group.ObjectEnumerableAssert.containsSequence(Object...)Example:
// an Iterable is used in the example but it would also work with an array Iterable<String> abc = newArrayList("a", "b", "c"); // assertions will pass assertThat(abc).endsWith("c") .endsWith("b", "c"); // assertions will fail assertThat(abc).endsWith("a"); assertThat(abc).endsWith("a", "b");- Specified by:
endsWithin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
first- the first element of the sequence of objects to look for.rest- the rest of the sequence of objects to look for.- Returns:
- this assertion object.
-
endsWith
public SELF endsWith(ELEMENT[] sequence)
Verifies that the actual group ends with the given sequence of objects, without any other objects between them. Similar to, but it also verifies that the last element in the sequence is also last element of the actual group.ObjectEnumerableAssert.containsSequence(Object...)Example:
// an Iterable is used in the example but it would also work with an array Iterable<String> abc = newArrayList("a", "b", "c"); // assertions will pass assertThat(abc).endsWith(new String[0]) .endsWith(new String[] {"c"}) .endsWith(new String[] {"b", "c"}); // assertions will fail assertThat(abc).endsWith(new String[] {"a"}); assertThat(abc).endsWith(new String[] {"a", "b"});- Specified by:
endsWithin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
sequence- the sequence of objects to look for.- Returns:
- this assertion object.
-
containsNull
public SELF containsNull()
Verifies that the actual group contains at least a null element.Example:
Iterable<String> abc = newArrayList("a", "b", "c"); Iterable<String> abNull = newArrayList("a", "b", null); // assertion will pass assertThat(abNull).containsNull(); // assertion will fail assertThat(abc).containsNull();- Specified by:
containsNullin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
doesNotContainNull
public SELF doesNotContainNull()
Verifies that the actual group does not contain null elements.Example:
Iterable<String> abc = newArrayList("a", "b", "c"); Iterable<String> abNull = newArrayList("a", "b", null); // assertion will pass assertThat(abc).doesNotContainNull(); // assertion will fail assertThat(abNull).doesNotContainNull();- Specified by:
doesNotContainNullin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
are
public SELF are(Condition<? super ELEMENT> condition)
Verifies that each element value satisfies the given condition.Example:
Iterable<String> abc = newArrayList("a", "b", "c"); Iterable<String> abcc = newArrayList("a", "b", "cc"); Condition<String> singleCharacterString = new Condition<>(s -> s.length() == 1, "single character String"); // assertion will pass assertThat(abc).are(singleCharacterString); // assertion will fail assertThat(abcc).are(singleCharacterString);- Specified by:
arein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
thisobject.
-
areNot
public SELF areNot(Condition<? super ELEMENT> condition)
Verifies that each element value does not satisfy the given condition.Example:
Iterable<String> abc = newArrayList("a", "b", "c"); Iterable<String> abcc = newArrayList("a", "b", "cc"); Condition<String> moreThanOneCharacter = = new Condition<>(s -> s.length() > 1, "more than one character"); // assertion will pass assertThat(abc).areNot(moreThanOneCharacter); // assertion will fail assertThat(abcc).areNot(moreThanOneCharacter);- Specified by:
areNotin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
thisobject.
-
have
public SELF have(Condition<? super ELEMENT> condition)
Verifies that all elements satisfy the given condition.Example:
Iterable<String> abc = newArrayList("a", "b", "c"); Iterable<String> abcc = newArrayList("a", "b", "cc"); Condition<String> onlyOneCharacter = = new Condition<>(s -> s.length() == 1, "only one character"); // assertion will pass assertThat(abc).have(onlyOneCharacter); // assertion will fail assertThat(abcc).have(onlyOneCharacter);- Specified by:
havein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
thisobject.
-
doNotHave
public SELF doNotHave(Condition<? super ELEMENT> condition)
Verifies that all elements do not satisfy the given condition.Example:
Iterable<String> abc = newArrayList("a", "b", "c"); Iterable<String> abcc = newArrayList("a", "b", "cc"); Condition<String> moreThanOneCharacter = = new Condition<>(s -> s.length() > 1, "more than one character"); // assertion will pass assertThat(abc).doNotHave(moreThanOneCharacter); // assertion will fail assertThat(abcc).doNotHave(moreThanOneCharacter);- Specified by:
doNotHavein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
thisobject.
-
areAtLeastOne
public SELF areAtLeastOne(Condition<? super ELEMENT> 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:
areAtLeastOnein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
thisassertion object.- See Also:
ObjectEnumerableAssert.haveAtLeast(int, Condition)
-
areAtLeast
public SELF areAtLeast(int times, Condition<? super ELEMENT> condition)
Verifies that there are at least n elements in the actual group satisfying the given condition.Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3); Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number"); // assertion will pass oneTwoThree.areAtLeast(2, oddNumber); // assertion will fail oneTwoThree.areAtLeast(3, oddNumber);- Specified by:
areAtLeastin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
times- the minimum number of times the condition should be verified.condition- the given condition.- Returns:
thisobject.
-
areAtMost
public SELF areAtMost(int times, Condition<? super ELEMENT> condition)
Verifies that there are at most n elements in the actual group satisfying the given condition.Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3); Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number"); // assertions will pass oneTwoThree.areAtMost(2, oddNumber) .areAtMost(3, oddNumber); // assertion will fail oneTwoThree.areAtMost(1, oddNumber);- Specified by:
areAtMostin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
times- the number of times the condition should be at most verified.condition- the given condition.- Returns:
thisobject.
-
areExactly
public SELF areExactly(int times, Condition<? super ELEMENT> condition)
Verifies that there are exactly n elements in the actual group satisfying the given condition.Example:
Iterable<Integer> oneTwoThree = newArrayList(1, 2, 3); Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number"); // assertion will pass oneTwoThree.areExactly(2, oddNumber); // assertions will fail oneTwoThree.areExactly(1, oddNumber); oneTwoThree.areExactly(3, oddNumber);- Specified by:
areExactlyin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
times- the exact number of times the condition should be verified.condition- the given condition.- Returns:
thisobject.
-
haveAtLeastOne
public SELF haveAtLeastOne(Condition<? super ELEMENT> 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:
Iterable<BasketBallPlayer> bullsPlayers = newArrayList(butler, rose); // potentialMvp is a Condition<BasketBallPlayer> assertThat(bullsPlayers).haveAtLeastOne(potentialMvp);- Specified by:
haveAtLeastOnein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
thisassertion object.- See Also:
ObjectEnumerableAssert.haveAtLeast(int, Condition)
-
haveAtLeast
public SELF haveAtLeast(int times, Condition<? super ELEMENT> condition)
Verifies that there are at least n elements in the actual group satisfying the given condition.Example:
This method is an alias forIterable<Integer> oneTwoThree = newArrayList(1, 2, 3); Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number"); // assertion will pass oneTwoThree.haveAtLeast(2, oddNumber); // assertion will fail oneTwoThree.haveAtLeast(3, oddNumber);ObjectEnumerableAssert.areAtLeast(int, Condition).- Specified by:
haveAtLeastin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
times- the minimum number of times the condition must hold.condition- the given condition.- Returns:
thisassertion object.
-
haveAtMost
public SELF haveAtMost(int times, Condition<? super ELEMENT> condition)
Verifies that there are at most n elements in the actual group satisfying the given condition.Example:
This method is an aliasIterable<Integer> oneTwoThree = newArrayList(1, 2, 3); Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number"); // assertions will pass oneTwoThree.haveAtMost(2, oddNumber); oneTwoThree.haveAtMost(3, oddNumber); // assertion will fail oneTwoThree.haveAtMost(1, oddNumber);ObjectEnumerableAssert.areAtMost(int, Condition).- Specified by:
haveAtMostin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
times- the maximum number of times the condition must hold.condition- the given condition.- Returns:
thisassertion object.
-
haveExactly
public SELF haveExactly(int times, Condition<? super ELEMENT> condition)
Verifies that there are exactly n elements in the actual group satisfying the given condition.Example:
This method is an aliasIterable<Integer> oneTwoThree = newArrayList(1, 2, 3); Condition<Integer> oddNumber = new Condition<>(value % 2 == 1, "odd number"); // assertion will pass oneTwoThree.haveExactly(2, oddNumber); // assertions will fail oneTwoThree.haveExactly(1, oddNumber); oneTwoThree.haveExactly(3, oddNumber);ObjectEnumerableAssert.areExactly(int, Condition).- Specified by:
haveExactlyin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
times- the exact number of times the condition must hold.condition- the given condition.- Returns:
thisassertion object.
-
hasAtLeastOneElementOfType
public SELF hasAtLeastOneElementOfType(Class<?> expectedType)
Verifies that at least one element in the actualIterablehas 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:
hasAtLeastOneElementOfTypein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
expectedType- the expected type.- Returns:
- this assertion object.
- Throws:
NullPointerException- if the given type isnull.AssertionError- if the actualObjectgroup does not have any elements of the given type.
-
hasOnlyElementsOfType
public SELF hasOnlyElementsOfType(Class<?> expectedType)
Verifies that all elements in the actualIterablehave the specified type (matching includes subclasses of the given type).Example:
List<Number> numbers = new ArrayList<Number>(); numbers.add(1); numbers.add(2); numbers.add(3); // successful assertions: assertThat(numbers).hasOnlyElementsOfType(Number.class); assertThat(numbers).hasOnlyElementsOfType(Integer.class); // assertion failure: assertThat(numbers).hasOnlyElementsOfType(Long.class);- Specified by:
hasOnlyElementsOfTypein interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
expectedType- the expected type.- Returns:
- this assertion object.
- Throws:
NullPointerException- if the given type isnull.AssertionError- if one element is not of the expected type.
-
doesNotHaveAnyElementsOfTypes
public SELF doesNotHaveAnyElementsOfTypes(Class<?>... unexpectedTypes)
Verifies that all elements in the actualIterabledo not have the specified types (including subclasses).Example:
List<Number> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3.0); // successful assertions: assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Float.class); // assertion failure: assertThat(numbers).doesNotHaveAnyElementsOfTypes(Long.class, Integer.class);- Specified by:
doesNotHaveAnyElementsOfTypesin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
unexpectedTypes- the not expected types.- Returns:
- this assertion object.
- Throws:
NullPointerException- if the given type isnull.AssertionError- if one element's type matches the given types.- Since:
- 2.9.0 / 3.9.0
-
hasOnlyElementsOfTypes
public SELF hasOnlyElementsOfTypes(Class<?>... types)
Verifies that all elements of the actual group are instances of the given types.Example:
Iterable<? extends Object> objects = Arrays.asList("foo", new StringBuilder()); // assertions will pass assertThat(objects).hasOnlyElementsOfTypes(CharSequence.class) .hasOnlyElementsOfTypes(String.class, StringBuilder.class); // assertions will fail assertThat(objects).hasOnlyElementsOfTypes(Number.class); assertThat(objects).hasOnlyElementsOfTypes(String.class, Number.class); assertThat(objects).hasOnlyElementsOfTypes(String.class);- Specified by:
hasOnlyElementsOfTypesin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
types- the expected classes and interfaces- Returns:
thisassertion object.
-
containsAll
public SELF containsAll(Iterable<? extends ELEMENT> iterable)
Verifies that the actual group contains all the elements of givenIterable, in any order.Example:
Iterable<String> abc = Arrays.asList("a", "b", "c"); // assertions will pass assertThat(abc).containsAll(Arrays.asList("b", "c")) .containsAll(Arrays.asList("a", "b", "c")); // assertions will fail assertThat(abc).containsAll(Arrays.asList("d")); assertThat(abc).containsAll(Arrays.asList("a", "b", "c", "d"));If you want to directly specify the elements to check, use
contains(Object...)instead.- Specified by:
containsAllin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
iterable- the givenIterablewe will get elements from.- Returns:
thisassertion object.
-
usingElementComparator
public SELF usingElementComparator(Comparator<? super ELEMENT> elementComparator)
Use given custom comparator instead of relying on actual type Aequalsmethod 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:
usingElementComparatorin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
elementComparator- the comparator to use for incoming assertion checks.- Returns:
thisassertion object.
-
usingExtendedByTypesElementComparator
private SELF usingExtendedByTypesElementComparator(Comparator<Object> elementComparator)
-
usingDefaultElementComparator
public SELF 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:
usingDefaultElementComparatorin interfaceEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
containsAnyOf
public SELF containsAnyOf(ELEMENT... values)
Verifies that the actualIterablecontains at least one of the given values.Example :
Iterable<String> abc = Arrays.asList("a", "b", "c"); // assertions will pass assertThat(abc).containsAnyOf("b") .containsAnyOf("b", "c") .containsAnyOf("a", "b", "c") .containsAnyOf("a", "b", "c", "d") .containsAnyOf("e", "f", "g", "b"); // assertions will fail assertThat(abc).containsAnyOf("d"); assertThat(abc).containsAnyOf("d", "e", "f", "g");- Specified by:
containsAnyOfin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the values whose at least one which is expected to be in theIterableunder test.- Returns:
thisassertion object.- Throws:
NullPointerException- if the array of values isnull.IllegalArgumentException- if the array of values is empty and theIterableunder test is not empty.AssertionError- if theIterableunder test isnull.AssertionError- if theIterableunder test does not contain any of the givenvalues.- Since:
- 2.9.0 / 3.9.0
-
containsAnyElementsOf
public SELF containsAnyElementsOf(Iterable<? extends ELEMENT> iterable)
Verifies that theIterableunder test contains at least one of the givenIterableelements.Example :
Iterable<String> abc = Arrays.asList("a", "b", "c"); // assertions will pass assertThat(abc).containsAnyElementsOf(Arrays.asList("b")) .containsAnyElementsOf(Arrays.asList("b", "c")) .containsAnyElementsOf(Arrays.asList("a", "b", "c")) .containsAnyElementsOf(Arrays.asList("a", "b", "c", "d")) .containsAnyElementsOf(Arrays.asList("e", "f", "g", "b")); // assertions will fail assertThat(abc).containsAnyElementsOf(Arrays.asList("d")); assertThat(abc).containsAnyElementsOf(Arrays.asList("d", "e", "f", "g"));- Specified by:
containsAnyElementsOfin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
iterable- the iterable whose at least one element is expected to be in theIterableunder test.- Returns:
thisassertion object.- Throws:
NullPointerException- if the iterable of expected values isnull.IllegalArgumentException- if the iterable of expected values is empty and theIterableunder test is not empty.AssertionError- if theIterableunder test isnull.AssertionError- if theIterableunder test does not contain any of elements from the givenIterable.- Since:
- 2.9.0 / 3.9.0
-
extracting
public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> extracting(String propertyOrField)
Extract the values of the given field or property from the Iterable's elements under test into a new Iterable, this new Iterable becoming the Iterable under test.It allows you to test a property/field of the Iterable's elements instead of testing the elements themselves, which can be be much less work !
Let's take a look at an example to make things clearer :
// build a list of TolkienCharacters: a TolkienCharacter has a name, and age and a Race (a specific class) // they can be public field or properties, both can be extracted. List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>(); fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA)); fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF)); fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF)); fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN); fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN)); // let's verify the names of the TolkienCharacters in fellowshipOfTheRing : assertThat(fellowshipOfTheRing).extracting("name") .contains("Boromir", "Gandalf", "Frodo") .doesNotContain("Sauron", "Elrond"); // you can extract nested properties/fields like the name of the race : assertThat(fellowshipOfTheRing).extracting("race.name") .contains("Hobbit", "Elf") .doesNotContain("Orc");A property with the given name is searched for first. If it doesn't exist a field with the given name is looked for. If the field does not exist an
IntrospectionErroris thrown. By default private fields are read but you can change this withAssertions.setAllowComparingPrivateFields(boolean). Trying to read a private field when it's not allowed leads to anIntrospectionError.Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under test, for example if it's a
HashSet, you won't be able to make any assumptions on the extracted values order.
Extracting also support maps, that is, instead of extracting values from an Object, it extracts maps values corresponding to the given keys.
Example:
Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee luke = new Employee(2L, new Name("Luke"), 22); Employee han = new Employee(3L, new Name("Han"), 31); // build two maps Map<String, Employee> map1 = new HashMap<>(); map1.put("key1", yoda); map1.put("key2", luke); Map<String, Employee> map2 = new HashMap<>(); map2.put("key1", yoda); map2.put("key2", han); // instead of a list of objects, we have a list of maps List<Map<String, Employee>> maps = asList(map1, map2); // extracting a property in that case = get values from maps using the property as a key assertThat(maps).extracting("key2").containsExactly(luke, han); assertThat(maps).extracting("key1").containsExactly(yoda, yoda); // type safe version assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han); // it works with several keys, extracted values being wrapped in a Tuple assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han)); // unknown keys leads to null (map behavior) assertThat(maps).extracting("bad key").containsExactly(null, null);- Parameters:
propertyOrField- the property/field to extract from the elements of 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 in one of the initial Iterable's element.
-
extractingResultOf
public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> extractingResultOf(String method)
Extract the result of given method invocation on the Iterable's elements under test into a new Iterable, this new Iterable becoming the Iterable under test.It allows you to test the method results of the Iterable's elements instead of testing the elements themselves. This is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String toString() or public String status() instead of public String getStatus()).
Let's take a look at an example to make things clearer :
Following requirements have to be met to extract method results:// 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 the great houses of Westeros: assertThat(greatHouses).extractingResultOf("sayTheWords") .contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar") .doesNotContain("Lannisters always pay their debts");- method has to be public,
- method cannot accept any arguments,
- method cannot return void.
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> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extractingResultOf(String method, Class<P> extractedType)
Extract the result of given method invocation on the Iterable's elements under test into a new list of the given class, this new List becoming the object under test.It allows you to test the method results of the Iterable's elements instead of testing the elements themselves, it is especially useful for classes that do not conform to the Java Bean's getter specification (i.e. public String toString() or public String status() instead of public String getStatus()).
Let's take an example to make things clearer :
Following requirements have to be met to extract method results:// 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 the great houses of Westeros: assertThat(greatHouses).extractingResultOf("sayTheWords", String.class) .contains("Winter is Coming", "We Do Not Sow", "Hear Me Roar") .doesNotContain("Lannisters always pay their debts");- method has to be public,
- method cannot accept any arguments,
- method cannot return void.
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.- Type Parameters:
P- the type of elements extracted.- Parameters:
method- the name of the method which result is to be extracted from the array under testextractedType- 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> AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extracting(String propertyOrField, Class<P> extractingType)
Extract the values of given field or property from the Iterable's elements under test into a new Iterable, this new Iterable becoming the Iterable under test.It allows you to test a property/field of the Iterable's elements instead of testing the elements themselves, which can be much less work !
Let's take an example to make things clearer :
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// 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");IntrospectionErroris thrown, by default private fields are read but you can change this withAssertions.setAllowComparingPrivateFields(boolean), trying to read a private field when it's not allowed leads to anIntrospectionError.Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under test, for example if it's a
HashSet, you won't be able to make any assumptions on the extracted values order.
Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values corresponding to the given keys.
Example:
Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee luke = new Employee(2L, new Name("Luke"), 22); Employee han = new Employee(3L, new Name("Han"), 31); // build two maps Map<String, Employee> map1 = new HashMap<>(); map1.put("key1", yoda); map1.put("key2", luke); Map<String, Employee> map2 = new HashMap<>(); map2.put("key1", yoda); map2.put("key2", han); // instead of a list of objects, we have a list of maps List<Map<String, Employee>> maps = asList(map1, map2); // extracting a property in that case = get values from maps using property as a key assertThat(maps).extracting(key2, Employee.class).containsExactly(luke, han); // non type safe version assertThat(maps).extracting("key2").containsExactly(luke, han); assertThat(maps).extracting("key1").containsExactly(yoda, yoda); // it works with several keys, extracted values being wrapped in a Tuple assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han)); // unknown keys leads to null (map behavior) assertThat(maps).extracting("bad key").containsExactly(null, null);- Type Parameters:
P- the type of elements extracted.- Parameters:
propertyOrField- the property/field to extract from the Iterable under testextractingType- 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 in one of the initial Iterable's element.
-
extracting
public AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> extracting(String... propertiesOrFields)
Extract the values of the given fields/properties from the Iterable's elements under test into a new Iterable composed of Tuples (a simple data structure), this new Iterable becoming the Iterable under test.It allows you to test fields/properties of the Iterable's elements instead of testing the elements themselves, which can be much less work!
The Tuple data corresponds to the extracted values of the given fields/properties, for instance if you ask to extract "id", "name" and "email" then each Tuple data will be composed of id, name and email extracted from the element of the initial Iterable (the Tuple's data order is the same as the given fields/properties order).
Let's take an example to make things clearer :
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// 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"));IntrospectionErroris thrown, by default private fields are read but you can change this withAssertions.setAllowComparingPrivateFields(boolean), trying to read a private field when it's not allowed leads to anIntrospectionError.Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under test, for example if it's a
HashSet, you won't be able to make any assumptions on the extracted values order.
Extracting also support maps, that is, instead of extracting values from an Object, it extract maps values corresponding to the given keys.
Example:
Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee luke = new Employee(2L, new Name("Luke"), 22); Employee han = new Employee(3L, new Name("Han"), 31); // build two maps Map<String, Employee> map1 = new HashMap<>(); map1.put("key1", yoda); map1.put("key2", luke); Map<String, Employee> map2 = new HashMap<>(); map2.put("key1", yoda); map2.put("key2", han); // instead of a list of objects, we have a list of maps List<Map<String, Employee>> maps = asList(map1, map2); // extracting a property in that case = get values from maps using property as a key assertThat(maps).extracting("key2").containsExactly(luke, han); assertThat(maps).extracting("key1").containsExactly(yoda, yoda); // it works with several keys, extracted values being wrapped in a Tuple assertThat(maps).extracting("key1", "key2").containsExactly(tuple(yoda, luke), tuple(yoda, han)); // unknown keys leads to null (map behavior) assertThat(maps).extracting("bad key").containsExactly(null, null);- Parameters:
propertiesOrFields- the properties/fields to extract from the elements of the 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 in one of the initial Iterable's element.
-
extracting
public <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(Function<? super ELEMENT,V> extractor)
Extract the values from Iterable's elements under test by applying an extracting function on them. 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 have a look at an example :
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under test, for example if it's a// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class) // they can be public field or properties, both can be extracted. List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>(); fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA)); fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF)); fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF)); fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN); fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN)); // fellowship has hobbitses, right, my presioussss? assertThat(fellowshipOfTheRing).extracting(TolkienCharacter::getRace).contains(HOBBIT);HashSet, you won't be able to make any assumptions on the extracted values order.- Type Parameters:
V- the type of elements extracted.- Parameters:
extractor- the object transforming input object to desired one- Returns:
- a new assertion object whose object under test is the list of values extracted
-
extracting
public <V,EXCEPTION extends Exception> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(ThrowingExtractor<? super ELEMENT,V,EXCEPTION> extractor)
Extract the values from Iterable's elements under test by applying an extracting function (which might throw an exception) on them. The returned iterable becomes a new object under test.Any checked exception raised in the extractor is rethrown wrapped in a
RuntimeException.It allows to test values from the elements in more safe way than by using
extracting(String), as it doesn't utilize introspection.Let's have a look at an example :
Note that the order of extracted property/field values is consistent with the iteration order of the Iterable under test, for example if it's a// Build a list of TolkienCharacter, a TolkienCharacter has a name, and age and a Race (a specific class) // they can be public field or properties, both can be extracted. List<TolkienCharacter> fellowshipOfTheRing = new ArrayList<TolkienCharacter>(); fellowshipOfTheRing.add(new TolkienCharacter("Frodo", 33, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Sam", 38, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Gandalf", 2020, MAIA)); fellowshipOfTheRing.add(new TolkienCharacter("Legolas", 1000, ELF)); fellowshipOfTheRing.add(new TolkienCharacter("Pippin", 28, HOBBIT)); fellowshipOfTheRing.add(new TolkienCharacter("Gimli", 139, DWARF)); fellowshipOfTheRing.add(new TolkienCharacter("Aragorn", 87, MAN); fellowshipOfTheRing.add(new TolkienCharacter("Boromir", 37, MAN)); assertThat(fellowshipOfTheRing).extracting(input -> { if (input.getAge() < 20) { throw new Exception("age < 20"); } return input.getName(); }).contains("Frodo");HashSet, you won't be able to make any assumptions on the extracted values order.- Type Parameters:
EXCEPTION- the exception type ofThrowingExtractorV- the type of elements extracted.- Parameters:
extractor- the object transforming input object to desired one- Returns:
- a new assertion object whose object under test is the list of values extracted
- Since:
- 3.7.0
-
newListAssertInstanceForMethodsChangingElementType
private <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> newListAssertInstanceForMethodsChangingElementType(List<V> values)
-
flatExtracting
public <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(Function<? super ELEMENT,? 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:
The order of extracted values is consistent with both the order of the collection itself, as well as the extracted collections.CartoonCharacter bart = new CartoonCharacter("Bart Simpson"); CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson"); CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson"); CartoonCharacter homer = new CartoonCharacter("Homer Simpson"); homer.getChildren().add(bart); homer.getChildren().add(lisa); homer.getChildren().add(maggie); CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone"); CartoonCharacter fred = new CartoonCharacter("Fred Flintstone"); fred.getChildren().add(pebbles); List<CartoonCharacter> parents = list(homer, fred); // check children property which is a List<CartoonCharacter> assertThat(parents).flatExtracting(CartoonCharacter::getChildren) .containsOnly(bart, lisa, maggie, pebbles);- Type Parameters:
V- the type of elements extracted.- Parameters:
extractor- the object transforming input object to anIterableof desired ones- Returns:
- a new assertion object whose object under test is the list of values extracted
- Throws:
NullPointerException- if one of theIterable's element is null.
-
flatExtracting
public <V,EXCEPTION extends Exception> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(ThrowingExtractor<? super ELEMENT,? extends Collection<V>,EXCEPTION> extractor)
Extract the Iterable values from Iterable's elements under test by applying an Iterable extracting function (which might throw a checked exception) 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:
The order of extracted values is consistent with both the order of the collection itself, as well as the extracted collections.CartoonCharacter bart = new CartoonCharacter("Bart Simpson"); CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson"); CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson"); CartoonCharacter homer = new CartoonCharacter("Homer Simpson"); homer.getChildren().add(bart); homer.getChildren().add(lisa); homer.getChildren().add(maggie); CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone"); CartoonCharacter fred = new CartoonCharacter("Fred Flintstone"); fred.getChildren().add(pebbles); List<CartoonCharacter> parents = list(homer, fred); // check children property where getChildren() can throw an Exception! assertThat(parents).flatExtracting(CartoonCharacter::getChildren) .containsOnly(bart, lisa, maggie, pebbles);- Type Parameters:
V- the type of elements extracted.EXCEPTION- the exception type ofThrowingExtractor- Parameters:
extractor- the object transforming input object to anIterableof desired ones- Returns:
- a new assertion object whose object under test is the list of values extracted
- Throws:
NullPointerException- if one of theIterable's element is null.- Since:
- 3.7.0
-
doFlatExtracting
private <V> AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> doFlatExtracting(Function<? super ELEMENT,? extends Collection<V>> extractor)
-
flatExtracting
public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(Function<? super ELEMENT,?>... extractors)
Extract multiple values from eachIterable's element according to the givenFunctions and concatenate/flatten the extracted values in a list that is used as the new object under test.If extracted values were not flattened, instead of a simple list like (given 2 extractors) :
element1.value1, element1.value2, element2.value1, element2.value2, ...
we would get a list of list like :list(element1.value1, element1.value2), list(element2.value1, element2.value2), ...
Code example:
The resulting extracted values list is ordered by// fellowshipOfTheRing is a List<TolkienCharacter> // values are extracted in order and flattened : age1, name1, age2, name2, age3 ... assertThat(fellowshipOfTheRing).flatExtracting(TolkienCharacter::getAge, TolkienCharacter::getName) .contains(33 ,"Frodo", 1000, "Legolas", 87, "Aragorn");Iterable's element first and then extracted values, this is why is in the example that age values come before names.- Parameters:
extractors- all the extractors to apply on each actualIterable's elements- Returns:
- a new assertion object whose object under test is a flattened list of all extracted values.
-
flatExtracting
public <EXCEPTION extends Exception> AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(ThrowingExtractor<? super ELEMENT,?,EXCEPTION>... extractors)
Extract multiple values from eachIterable's element according to the givenThrowingExtractors and concatenate/flatten the extracted values in a list that is used as the new object under test.If extracted values were not flattened, instead of a simple list like (given 2 extractors) :
element1.value1, element1.value2, element2.value1, element2.value2, ...
we would get a list of list like :list(element1.value1, element1.value2), list(element2.value1, element2.value2), ...
Code example:
The resulting extracted values list is ordered by// fellowshipOfTheRing is a List<TolkienCharacter> // values are extracted in order and flattened : age1, name1, age2, name2, age3 ... assertThat(fellowshipOfTheRing).flatExtracting(input -> { if (input.getAge() < 20) { throw new Exception("age < 20"); } return input.getName(); }, input2 -> { if (input2.getAge() < 20) { throw new Exception("age < 20"); } return input2.getAge(); }).contains(33 ,"Frodo", 1000, "Legolas", 87, "Aragorn");Iterable's element first and then extracted values, this is why is in the example that age values come before names.- Type Parameters:
EXCEPTION- the exception type ofThrowingExtractor- Parameters:
extractors- all the extractors to apply on each actualIterable's elements- Returns:
- a new assertion object whose object under test is a flattened list of all extracted values.
- Since:
- 3.7.0
-
flatExtracting
public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(String fieldOrPropertyName)
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.It allows testing the elements of extracting values that are represented by iterables or arrays.
For example:
The order of extracted values is consisted with both the order of the collection itself, as well as the extracted collections.CartoonCharacter bart = new CartoonCharacter("Bart Simpson"); CartoonCharacter lisa = new CartoonCharacter("Lisa Simpson"); CartoonCharacter maggie = new CartoonCharacter("Maggie Simpson"); CartoonCharacter homer = new CartoonCharacter("Homer Simpson"); homer.getChildren().add(bart); homer.getChildren().add(lisa); homer.getChildren().add(maggie); CartoonCharacter pebbles = new CartoonCharacter("Pebbles Flintstone"); CartoonCharacter fred = new CartoonCharacter("Fred Flintstone"); fred.getChildren().add(pebbles); List<CartoonCharacter> parents = list(homer, fred); // check children which is a List<CartoonCharacter> assertThat(parents).flatExtracting("children") .containsOnly(bart, lisa, maggie, pebbles);- Parameters:
fieldOrPropertyName- the object transforming input object to an Iterable of desired ones- Returns:
- a new assertion object whose object under test is the list of values extracted
- Throws:
IllegalArgumentException- if one of the extracted property value was not an array or an iterable.
-
extracting
public AbstractListAssert<?,List<? extends Tuple>,Tuple,ObjectAssert<Tuple>> extracting(Function<? super ELEMENT,?>... extractors)
Use the givenFunctions to extract the values from theIterable's elements into a newIterablecomposed ofTuples (a simple data structure containing the extracted values), this newIterablebecoming the object under test.It allows you to test values from the
Iterable's elements instead of testing the elements themselves, which sometimes can be much less work!The Tuple data 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 a look at an example to make things clearer :
You can use lambda expression or a method reference to extract the expected values.// 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));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.- Parameters:
extractors- the extractor functions to extract a value from an element of the Iterable under test.- Returns:
- a new assertion object whose object under test is the list of Tuples containing the extracted values.
-
flatExtracting
public AbstractListAssert<?,List<? extends Object>,Object,ObjectAssert<Object>> flatExtracting(String... fieldOrPropertyNames)
Extract the given property/field values from eachIterable's element and flatten the extracted values in a list that is used as the new object under test.Given 2 properties, if the extracted values were not flattened, instead having a simple list like :
element1.value1, element1.value2, element2.value1, element2.value2, ...
... we would get a list of list :list(element1.value1, element1.value2), list(element2.value1, element2.value2), ...
Code example:
// fellowshipOfTheRing is a List<TolkienCharacter> // values are extracted in order and flattened : age1, name1, age2, name2, age3 ... assertThat(fellowshipOfTheRing).flatExtracting("age", "name") .contains(33 ,"Frodo", 1000, "Legolas", 87, "Aragorn");- Parameters:
fieldOrPropertyNames- the field and/or property names to extract from each actualIterable's element- Returns:
- a new assertion object whose object under test is a flattened list of all extracted values.
- Throws:
IllegalArgumentException- if fieldOrPropertyNames vararg is null or empty- Since:
- 2.5.0 / 3.5.0
-
containsExactlyElementsOf
public SELF containsExactlyElementsOf(Iterable<? extends ELEMENT> iterable)
Same asObjectEnumerableAssert.containsExactly(Object...)but handle theIterableto array conversion : verifies that actual contains exactly the elements of the given iterable and nothing else in the same order.Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass assertThat(elvesRings).containsExactlyElementsOf(newLinkedList(vilya, nenya, narya)); // assertion will fail as actual and expected order differ assertThat(elvesRings).containsExactlyElementsOf(newLinkedList(nenya, vilya, narya));If you want to directly specify the elements to check, use
containsExactly(Object...)instead.- Specified by:
containsExactlyElementsOfin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
iterable- the givenIterablewe will get elements from.- Returns:
thisassertion object.
-
containsOnlyElementsOf
public SELF containsOnlyElementsOf(Iterable<? extends ELEMENT> iterable)
Same semantic asObjectEnumerableAssert.containsOnly(Object[]): verifies that actual contains all the elements of the given iterable and nothing else, in any order and ignoring duplicates (i.e. once a value is found, its duplicates are also considered found).Use
ObjectEnumerableAssert.isSubsetOf(Iterable)to check that actual is a subset of given iterableExample:
Iterable<Ring> rings = newArrayList(nenya, vilya); // assertion will pass assertThat(rings).containsOnlyElementsOf(newArrayList(nenya, vilya)) .containsOnlyElementsOf(newArrayList(nenya, nenya, vilya, vilya)); assertThat(newArrayList(nenya, nenya, vilya, vilya)).containsOnlyElementsOf(rings); // assertion will fail as actual does not contain narya assertThat(rings).containsOnlyElementsOf(newLinkedList(nenya, vilya, narya)); // assertion will fail as actual contains nenya assertThat(rings).containsOnlyElementsOf(newLinkedList(vilya));If you want to directly specify the elements to check, use
containsOnly(Object...)instead.- Specified by:
containsOnlyElementsOfin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
iterable- the givenIterablewe will get elements from.- Returns:
thisassertion object.
-
hasSameElementsAs
public SELF hasSameElementsAs(Iterable<? extends ELEMENT> iterable)
An alias ofObjectEnumerableAssert.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)) .hasSameElementsAs(newArrayList(nenya, narya, vilya, nenya)); // assertions will fail: assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya)); assertThat(elvesRings).hasSameElementsAs(newArrayList(nenya, narya, vilya, oneRing));- Specified by:
hasSameElementsAsin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
iterable- the Iterable whose elements we expect to be present- Returns:
- this assertion object
-
usingComparatorForElementFieldsWithNames
public <T> SELF usingComparatorForElementFieldsWithNames(Comparator<T> comparator, String... elementPropertyOrFieldNames)
Allows to set a comparator to compare properties or fields of elements with the given names. A typical usage is for comparing fields of numeric type at a given precision.To be used, comparators need to be specified by this method before calling any of:
usingFieldByFieldElementComparator()usingElementComparatorOnFields(java.lang.String...)usingElementComparatorIgnoringFields(java.lang.String...)usingRecursiveFieldByFieldElementComparator()
Comparators specified by this method have precedence over comparators specified by
usingComparatorForElementFieldsWithType.Example:
public class TolkienCharacter { private String name; private double height; // constructor omitted } TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2); TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3); TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9); Comparator<Double> closeEnough = new Comparator<Double>() { double precision = 0.5; public int compare(Double d1, Double d2) { return Math.abs(d1 - d2) <= precision ? 0 : 1; } }; // assertions will pass assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height") .usingFieldByFieldElementComparator() .contains(tallerFrodo); assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height") .usingElementComparatorOnFields("height") .contains(tallerFrodo); assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height") .usingElementComparatorIgnoringFields("name") .contains(tallerFrodo); assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height") .usingRecursiveFieldByFieldElementComparator() .contains(tallerFrodo); // assertion will fail assertThat(asList(frodo)).usingComparatorForElementFieldsWithNames(closeEnough, "height") .usingFieldByFieldElementComparator() .containsExactly(reallyTallFrodo);- Type Parameters:
T- the type of elements to compare.- Parameters:
comparator- theComparatorto useelementPropertyOrFieldNames- the names of the properties and/or fields of the elements the comparator should be used for- Returns:
thisassertions object- Since:
- 2.5.0 / 3.5.0
-
usingComparatorForElementFieldsWithType
public <T> SELF usingComparatorForElementFieldsWithType(Comparator<T> comparator, Class<T> type)
Allows to set a specific comparator to compare properties or fields of elements with the given type. A typical usage is for comparing fields of numeric type at a given precision.To be used, comparators need to be specified by this method before calling any of:
usingFieldByFieldElementComparator()usingElementComparatorOnFields(java.lang.String...)usingElementComparatorIgnoringFields(java.lang.String...)usingRecursiveFieldByFieldElementComparator()
Comparators specified by
usingComparatorForElementFieldsWithNameshave precedence over comparators specified by this method.Example:
public class TolkienCharacter { private String name; private double height; // constructor omitted } TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2); TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3); TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9); Comparator<Double> closeEnough = new Comparator<Double>() { double precision = 0.5; public int compare(Double d1, Double d2) { return Math.abs(d1 - d2) <= precision ? 0 : 1; } }; // assertions will pass assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class) .usingFieldByFieldElementComparator() .contains(tallerFrodo); assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class) .usingElementComparatorOnFields("height") .contains(tallerFrodo); assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class) .usingElementComparatorIgnoringFields("name") .contains(tallerFrodo); assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class) .usingRecursiveFieldByFieldElementComparator() .contains(tallerFrodo); // assertion will fail assertThat(Arrays.asList(frodo)).usingComparatorForElementFieldsWithType(closeEnough, Double.class) .usingFieldByFieldElementComparator() .contains(reallyTallFrodo);- Type Parameters:
T- the type of elements to compare.- Parameters:
comparator- theComparatorto usetype- theClassof the type of the element fields the comparator should be used for- Returns:
thisassertions object- Since:
- 2.5.0 / 3.5.0
-
usingComparatorForType
public <T> SELF usingComparatorForType(Comparator<T> comparator, Class<T> type)
Allows to set a specific comparator for the given type of elements or their fields. ExtendsusingComparatorForElementFieldsWithType(java.util.Comparator<T>, java.lang.Class<T>)by applying comparator specified for given type to elements themselves, not only to their fields.Usage of this method affects comparators set by next methods:
usingFieldByFieldElementComparator()usingElementComparatorOnFields(java.lang.String...)usingElementComparatorIgnoringFields(java.lang.String...)usingRecursiveFieldByFieldElementComparator()
Example:
// assertion will pass assertThat(asList("some", new BigDecimal("4.2"))) .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class) .contains(new BigDecimal("4.20"));- Type Parameters:
T- the type of elements to compare.- Parameters:
comparator- theComparatorto usetype- theClassof the type of the element or element fields the comparator should be used for- Returns:
thisassertions object- Since:
- 2.9.0 / 3.9.0
-
usingFieldByFieldElementComparator
public SELF usingFieldByFieldElementComparator()
Use field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type Aequalsmethod to compare group elements for incoming assertion checks. Private fields are included but this can be disabled usingAssertions.setAllowExtractingPrivateFields(boolean).This can be handy if
equalsmethod 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
equalsmethod.You can specify a custom comparator per name or type of element field with
usingComparatorForElementFieldsWithNames(Comparator, String...)andusingComparatorForElementFieldsWithType(Comparator, Class).Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT); // Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references assertThat(newArrayList(frodo)).contains(frodoClone); // frodo and frodoClone are equals when doing a field by field comparison. assertThat(newArrayList(frodo)).usingFieldByFieldElementComparator().contains(frodoClone);- Returns:
thisassertion object.
-
usingRecursiveFieldByFieldElementComparator
public SELF usingRecursiveFieldByFieldElementComparator()
Use a recursive field/property by field/property comparison (including inherited fields/properties) instead of relying on actual typeequalsmethod to compare group elements for incoming assertion checks. This can be useful if actual'sequalsimplementation does not suit you.The recursive property/field comparison is not applied on fields having a custom
equalsimplementation, i.e. the overriddenequalsmethod will be used instead of a field/property by field/property comparison.The recursive comparison handles cycles.
You can specify a custom comparator per (nested) name or type of element field with
usingComparatorForElementFieldsWithNamesandusingComparatorForElementFieldsWithType.The objects to compare can be of different types but must have the same properties/fields. For example if actual object has a
nameString field, the other object must also have one.If an object has a field and a property with the same name, the property value will be used over the field.
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT); frodo.setFriend(pippin); pippin.setFriend(frodo); TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter pippinClone = new TolkienCharacter("Pippin", 28, HOBBIT); frodoClone.setFriend(pippinClone); pippinClone.setFriend(frodoClone); List<TolkienCharacter> hobbits = Arrays.asList(frodo, pippin); // fails if equals has not been overridden in TolkienCharacter as it would compares object references assertThat(hobbits).contains(frodoClone, pippinClone); // frodo/frodoClone and pippin/pippinClone are equals when doing a recursive property/field by property/field comparison assertThat(hobbits).usingRecursiveFieldByFieldElementComparator() .contains(frodoClone, pippinClone);- Returns:
thisassertion object.- Since:
- 2.5.0 / 3.5.0
-
usingElementComparatorOnFields
public SELF 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 Aequalsmethod to compare group elements for incoming assertion checks. Private fields are included but this can be disabled usingAssertions.setAllowExtractingPrivateFields(boolean).This can be handy if
equalsmethod of the objects to compare does not suit you.You can specify a custom comparator per name or type of element field with
usingComparatorForElementFieldsWithNames(Comparator, String...)andusingComparatorForElementFieldsWithType(Comparator, Class).Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared to the other field/property using its
Example:equalsmethod.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- Parameters:
fields- the fields/properties to compare using element comparators- Returns:
thisassertion object.
-
usingComparisonStrategy
protected SELF usingComparisonStrategy(ComparisonStrategy comparisonStrategy)
-
usingElementComparatorIgnoringFields
public SELF usingElementComparatorIgnoringFields(String... fields)
Use field/property by field/property comparison on all fields/properties except the given ones (including inherited fields/properties) instead of relying on actual type Aequalsmethod to compare group elements for incoming assertion checks. Private fields are included but this can be disabled usingAssertions.setAllowExtractingPrivateFields(boolean).This can be handy if
equalsmethod of the objects to compare does not suit you.You can specify a custom comparator per name or type of element field with
usingComparatorForElementFieldsWithNames(Comparator, String...)andusingComparatorForElementFieldsWithType(Comparator, Class).Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared to the other field/property using its
Example:equalsmethod.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- Parameters:
fields- the fields/properties to compare using element comparators- Returns:
thisassertion object.
-
inHexadecimal
public SELF 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
With standard error message:final List<Byte> bytes = newArrayList((byte) 0x10, (byte) 0x20);
With Hexadecimal error message:assertThat(bytes).contains((byte) 0x30); Expecting: <[16, 32]> to contain: <[48]> but could not find: <[48]>assertThat(bytes).inHexadecimal().contains((byte) 0x30); Expecting: <[0x10, 0x20]> to contain: <[0x30]> but could not find: <[0x30]>- Overrides:
inHexadecimalin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
inBinary
public SELF inBinary()
Enable binary representation of Iterable elements instead of standard representation in error messages.Example:
With standard error message:final List<Byte> bytes = newArrayList((byte) 0x10, (byte) 0x20);
With binary error message:assertThat(bytes).contains((byte) 0x30); Expecting: <[16, 32]> to contain: <[48]> but could not find: <[48]>assertThat(bytes).inBinary().contains((byte) 0x30); Expecting: <[0b00010000, 0b00100000]> to contain: <[0b00110000]> but could not find: <[0b00110000]>- Overrides:
inBinaryin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
filteredOn
public SELF filteredOn(String propertyOrFieldName, Object expectedValue)
Filter the iterable under test keeping only elements having a property or field equal toexpectedValue, the property/field is specified bypropertyOrFieldNameparameter.The filter first tries to get the value from a property (named
propertyOrFieldName), if no such property exists it tries to read the value from a field. Reading private fields is supported by default, this can be globally disabled by callingAssertions.setAllowExtractingPrivateFields(false).When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check all employees 800 years old (yes, special employees):
Nested properties/fields are supported:Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); Employee noname = new Employee(4L, null, 50); List<Employee> employees = newArrayList(yoda, luke, obiwan, noname); assertThat(employees).filteredOn("age", 800) .containsOnly(yoda, obiwan);// Name is bean class with 'first' and 'last' String properties // name is null for noname => it does not match the filter on "name.first" assertThat(employees).filteredOn("name.first", "Luke") .containsOnly(luke); assertThat(employees).filteredOn("name.last", "Vader") .isEmpty();If you want to filter on null value, use
filteredOnNull(String)as Java will resolve the call tofilteredOn(String, FilterOperator)instead of this method.An
IntrospectionErroris thrown if the given propertyOrFieldName can't be found in one of the iterable elements.You can chain filters:
If you need more complex filter, use// 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);filteredOn(Predicate)orfilteredOn(Condition).- Parameters:
propertyOrFieldName- the name of the property or field to readexpectedValue- the value to compare element's property or field with- Returns:
- a new assertion object with the filtered iterable under test
- Throws:
IllegalArgumentException- if the given propertyOrFieldName isnullor empty.IntrospectionError- if the given propertyOrFieldName can't be found in one of the iterable elements.
-
filteredOnNull
public SELF filteredOnNull(String propertyOrFieldName)
Filter the iterable under test keeping only elements whose property or field specified bypropertyOrFieldNameis 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 callingAssertions.setAllowExtractingPrivateFields(false).When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check all employees 800 years old (yes, special employees):
Nested properties/fields are supported:Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); Employee noname = new Employee(4L, null, 50); List<Employee> employees = newArrayList(yoda, luke, obiwan, noname); assertThat(employees).filteredOnNull("name") .containsOnly(noname);
An// Name is bean class with 'first' and 'last' String properties assertThat(employees).filteredOnNull("name.last") .containsOnly(yoda, obiwan, noname);IntrospectionErroris thrown if the given propertyOrFieldName can't be found in one of the iterable elements.If you need more complex filter, use
filteredOn(Predicate)orfilteredOn(Condition).- Parameters:
propertyOrFieldName- the name of the property or field to read- Returns:
- a new assertion object with the filtered iterable under test
- Throws:
IntrospectionError- if the given propertyOrFieldName can't be found in one of the iterable elements.
-
filteredOn
public SELF filteredOn(String propertyOrFieldName, FilterOperator<?> filterOperator)
Filter the iterable under test keeping only elements having a property or field matching the filter expressed with theFilterOperator, the property/field is specified bypropertyOrFieldNameparameter.The existing filters are :
Whatever filter is applied, it first tries to get the value from a property (named
propertyOrFieldName), if no such property exists it tries to read the value from a field. Reading private fields is supported by default, this can be globally disabled by callingAssertions.setAllowExtractingPrivateFields(false).When reading nested property/field, if an intermediate value is null the whole nested property/field is considered to be null, thus reading "address.street.name" value will return null if "street" value is null.
As an example, let's check stuff on some special employees :
AnEmployee yoda = new Employee(1L, new Name("Yoda"), 800); Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); 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);IntrospectionErroris 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:
If you need more complex filter, use// 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);filteredOn(Predicate)orfilteredOn(Condition).- Parameters:
propertyOrFieldName- the name of the property or field to readfilterOperator- the filter operator to apply- Returns:
- a new assertion object with the filtered iterable under test
- Throws:
IllegalArgumentException- if the given propertyOrFieldName isnullor empty.
-
filteredOn
public SELF filteredOn(Condition<? super ELEMENT> condition)
Filter the iterable under test keeping only elements matching the givenCondition.If you prefer
PredicateoverCondition, usefilteredOn(Predicate).Example : check old employees whose age > 100:
You can combineEmployee yoda = new Employee(1L, new Name("Yoda"), 800); Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); Employee noname = new Employee(4L, null, 50); 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);Conditionwith condition operator likeNot:// 'not' filter is statically imported from Assertions.not assertThat(employees).filteredOn(not(oldEmployees)) .contains(luke, noname);- Parameters:
condition- the filter condition / predicate- Returns:
- a new assertion object with the filtered iterable under test
- Throws:
IllegalArgumentException- if the given condition isnull.
-
filteredOnAssertions
public SELF filteredOnAssertions(Consumer<? super ELEMENT> elementAssertions)
Filter the iterable under test keeping only elements matching the given assertions specified with aConsumer.Example : check young hobbits whose age < 34:
TolkienCharacter pippin = new TolkienCharacter("Pippin", 28, HOBBIT); TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter merry = new TolkienCharacter("Merry", 36, HOBBIT); TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT); List<TolkienCharacter> hobbits = list(frodo, sam, merry, pippin); assertThat(hobbits).filteredOnAssertions(hobbit -> assertThat(hobbit.age).isLessThan(34)) .containsOnly(frodo, pippin);- Parameters:
elementAssertions- containing AssertJ assertions to filter on- Returns:
- a new assertion object with the filtered iterable under test
- Throws:
IllegalArgumentException- if the given predicate isnull.- Since:
- 3.11.0
-
first
public ELEMENT_ASSERT first()
Navigate and allow to perform assertions on the first element of theIterableunder test.By default available assertions after
first()areObjectassertions, it is possible though to get more specific assertions if you createIterableAssertwith either:- the element assert class, see:
assertThat(Iterable, element assert class) - an assert factory used that knows how to create elements assertion, see:
assertThat(Iterable, element assert factory)
Example: default
Objectassertions// default iterable assert => element assert is ObjectAssert Iterable<TolkienCharacter> hobbits = newArrayList(frodo, sam, pippin); // assertion succeeds, only Object assertions are available after first() assertThat(hobbits).first() .isEqualTo(frodo); // assertion fails assertThat(hobbits).first() .isEqualTo(pippin);If you have created the Iterable assertion using an
AssertFactoryor the element assert class, you will be able to chainfirst()with more specific typed assertion.Example: use of
Stringassertions afterfirst()Iterable<String> hobbits = newArrayList("frodo", "sam", "pippin"); // assertion succeeds // String assertions are available after first() assertThat(hobbits, StringAssert.class).first() .startsWith("fro") .endsWith("do"); // assertion fails assertThat(hobbits, StringAssert.class).first() .startsWith("pip");- Returns:
- the assertion on the first element
- Throws:
AssertionError- if the actualIterableis empty.- Since:
- 2.5.0 / 3.5.0
- the element assert class, see:
-
last
public ELEMENT_ASSERT last()
Navigate and allow to perform assertions on the last element of theIterableunder test.By default available assertions after
last()areObjectassertions, it is possible though to get more specific assertions if you createIterableAssertwith either:- the element assert class, see:
assertThat(Iterable, element assert class) - an assert factory used that knows how to create elements assertion, see:
assertThat(Iterable, element assert factory)
Example: default
Objectassertions// default iterable assert => element assert is ObjectAssert Iterable<TolkienCharacter> hobbits = newArrayList(frodo, sam, pippin); // assertion succeeds, only Object assertions are available after last() assertThat(hobbits).last() .isEqualTo(pippin); // assertion fails assertThat(hobbits).last() .isEqualTo(frodo);If you have created the Iterable assertion using an
AssertFactoryor the element assert class, you will be able to chainlast()with more specific typed assertion.Example: use of
Stringassertions afterlast()Iterable<String> hobbits = newArrayList("frodo", "sam", "pippin"); // assertion succeeds // String assertions are available after last() assertThat(hobbits, StringAssert.class).last() .startsWith("pi") .endsWith("in"); // assertion fails assertThat(hobbits, StringAssert.class).last() .startsWith("fro");- Returns:
- the assertion on the first element
- Throws:
AssertionError- if the actualIterableis empty.- Since:
- 2.5.0 / 3.5.0
- the element assert class, see:
-
lastElement
private ELEMENT lastElement()
-
element
public ELEMENT_ASSERT element(int index)
Navigate and allow to perform assertions on the chosen element of theIterableunder test.By default available assertions after
element(index)areObjectassertions, it is possible though to get more specific assertions if you createIterableAssertwith either:- the element assert class, see:
assertThat(Iterable, element assert class) - an assert factory used that knows how to create elements assertion, see:
assertThat(Iterable, element assert factory)
Example: default
Objectassertions// default iterable assert => element assert is ObjectAssert Iterable<TolkienCharacter> hobbits = newArrayList(frodo, sam, pippin); // assertion succeeds, only Object assertions are available after element(index) assertThat(hobbits).element(1) .isEqualTo(sam); // assertion fails assertThat(hobbits).element(1) .isEqualTo(pippin);If you have created the Iterable assertion using an
AssertFactoryor the element assert class, you will be able to chainelement(index)with more specific typed assertion.Example: use of
Stringassertions afterelement(index)Iterable<String> hobbits = newArrayList("frodo", "sam", "pippin"); // assertion succeeds // String assertions are available after element(index) assertThat(hobbits, StringAssert.class).element(1) .startsWith("sa") .endsWith("am"); // assertion fails assertThat(hobbits, StringAssert.class).element(1) .startsWith("fro");- Parameters:
index- the element's index- Returns:
- the assertion on the given element
- Throws:
AssertionError- if the given index is out of bound.- Since:
- 2.5.0 / 3.5.0
- the element assert class, see:
-
toAssert
protected abstract ELEMENT_ASSERT toAssert(ELEMENT value, String description)
-
filteredOn
public SELF filteredOn(Predicate<? super ELEMENT> predicate)
Filter the iterable under test keeping only elements matching the givenPredicate.Example : check old employees whose age > 100:
Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); List<Employee> employees = newArrayList(yoda, luke, obiwan); assertThat(employees).filteredOn(employee -> employee.getAge() > 100) .containsOnly(yoda, obiwan);- Parameters:
predicate- the filter predicate- Returns:
- a new assertion object with the filtered iterable under test
- Throws:
IllegalArgumentException- if the given predicate isnull.
-
allMatch
public SELF allMatch(Predicate<? super ELEMENT> predicate)
Verifies that all the elements of actual match the givenPredicate.Example :
Note that you can achieve the same result withIterable<String> abc = newArrayList("a", "b", "c"); Iterable<String> abcc = newArrayList("a", "b", "cc"); // assertion will pass assertThat(abc).allMatch(s -> s.length() == 1); // assertion will fail assertThat(abcc).allMatch(s -> s.length() == 1);are(Condition)orhave(Condition).- Specified by:
allMatchin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
predicate- the givenPredicate.- Returns:
thisobject.
-
allMatch
public SELF allMatch(Predicate<? super ELEMENT> predicate, String predicateDescription)
Verifies that all the elements of actual match the givenPredicate. The predicate description is used to get an informative error message.Example :
The message of the failed assertion would be:Iterable<String> abc = newArrayList("a", "b", "c"); Iterable<String> abcc = newArrayList("a", "b", "cc"); // assertion will pass assertThat(abc).allMatch(s -> s.length() == 1, "length of 1"); // assertion will fail assertThat(abcc).allMatch(s -> s.length() == 1, "length of 1");Expecting all elements of: <["a", "b", "cc"]> to match 'length of 1' predicate but this element did not: <"cc">- Specified by:
allMatchin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
predicate- the givenPredicate.predicateDescription- a description of thePredicateused in the error message- Returns:
thisobject.
-
allSatisfy
public SELF allSatisfy(Consumer<? super ELEMENT> requirements)
Verifies that all the elements satisfy given requirements expressed as aConsumer.This is useful to perform a group of assertions on elements.
Example:
assertThat(myIcelanderFriends).allSatisfy(person -> { assertThat(person.getCountry()).isEqualTo("Iceland"); assertThat(person.getPhoneCountryCode()).isEqualTo("+354"); });If the actual iterable/array is empty, this assertion succeeds as there is no elements to check.
- Specified by:
allSatisfyin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
requirements- the givenConsumer.- Returns:
thisobject.
-
anyMatch
public SELF anyMatch(Predicate<? super ELEMENT> predicate)
Description copied from interface:ObjectEnumerableAssertVerifies whether any elements match the providedPredicate.Example :
Note that you can achieve the same result withIterable<String> abcc = newArrayList("a", "b", "cc"); // assertion will pass assertThat(abcc).anyMatch(s -> s.length() == 2); // assertion will fail assertThat(abcc).anyMatch(s -> s.length() > 2);areAtLeastOne(Condition)orhaveAtLeastOne(Condition).- Specified by:
anyMatchin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
predicate- the givenPredicate.- Returns:
thisobject.
-
zipSatisfy
public <OTHER_ELEMENT> SELF zipSatisfy(Iterable<OTHER_ELEMENT> other, BiConsumer<? super ELEMENT,OTHER_ELEMENT> zipRequirements)
Verifies that the zipped pairs of actual and other elements, i.e: (actual 1st element, other 1st element), (actual 2nd element, other 2nd element), ... all satisfy the givenzipRequirements.This assertion assumes that actual and other have the same size but they can contain different type of elements making it handy to compare objects converted to another type, for example Domain and View/DTO objects.
Example:
List<Adress> addressModels = findGoodRestaurants(); List<AdressView> addressViews = convertToView(addressModels); // compare addressViews and addressModels respective paired elements. assertThat(addressViews).zipSatisfy(addressModels, (AdressView view, Adress model) -> { assertThat(view.getZipcode() + ' ' + view.getCity()).isEqualTo(model.getCityLine()); assertThat(view.getStreet()).isEqualTo(model.getStreet().toUpperCase()); });- Type Parameters:
OTHER_ELEMENT- the type of the other iterable elements.- Parameters:
other- the iterable to zip actual with.zipRequirements- the given requirements that each pair must satisfy.- Returns:
thisassertion object.- Throws:
NullPointerException- if the given zipRequirementsBiConsumerisnull.NullPointerException- if the other iterable to zip actual with isnull.AssertionError- if theIterableunder test isnull.AssertionError- if actual and other don't have the same size.AssertionError- if one or more pairs don't satisfy the given requirements.- Since:
- 3.9.0
-
anySatisfy
public SELF anySatisfy(Consumer<? super ELEMENT> requirements)
Verifies that at least one element satisfies the given requirements expressed as aConsumer.This is useful to check that a group of assertions is verified by (at least) one element.
If the group of elements to assert is empty, the assertion will fail.
Example:
// assume that one icelander in myIcelanderFriends has a name finishing by 'son' assertThat(myIcelanderFriends).anySatisfy(person -> { assertThat(person.getCountry()).isEqualTo("Iceland"); assertThat(person.getSurname()).endsWith("son"); }); // assertion fails for empty group, whatever the requirements are. assertThat(emptyGroup).anySatisfy($ -> assertThat(true).isTrue());- Specified by:
anySatisfyin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
requirements- the givenConsumer.- Returns:
thisobject.
-
noneSatisfy
public SELF noneSatisfy(Consumer<? super ELEMENT> restrictions)
Verifies that no elements satisfy the given restrictions expressed as aConsumer.Example:
Note that this assertion succeeds if the group (collection, array, ...) is empty whatever the restrictions are.// assume that all icelander in myIcelanderFriends are not from Brazil assertThat(myIcelanderFriends).noneSatisfy(person -> { assertThat(person.getCountry()).isEqualTo("Brazil"); });- Specified by:
noneSatisfyin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
restrictions- the given restrictions asConsumerthat no elements should met.- Returns:
thisobject.
-
as
public SELF as(String description, Object... args)
Description copied from class:AbstractAssertSets the description of the assertion that is going to be called after.You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
The description follows
String.format(String, Object...)syntax.Example :
try { // set a bad age to Mr Frodo which is really 33 years old. frodo.setAge(50); // specify a test description (call as() before the assertion !), it supports String format syntax. assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33); } catch (AssertionError e) { assertThat(e).hasMessage("[check Frodo's age] expected:<[33]> but was:<[50]>"); }- Specified by:
asin interfaceDescriptable<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>>- Overrides:
asin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
description- the new description to set.args- optional parameter if description is a format String.- Returns:
thisobject.- See Also:
Descriptable.describedAs(String, Object...)
-
as
public SELF as(Description description)
Description copied from class:AbstractAssertSets the description of the assertion that is going to be called after.You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
This overloaded version of "describedAs" offers more flexibility than the one taking a
Stringby allowing users to pass their own implementation of a description. For example, a description that creates its value lazily, only when an assertion failure occurs.- Specified by:
asin interfaceDescriptable<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>>- Overrides:
asin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
description- the new description to set.- Returns:
thisobject.- See Also:
Descriptable.describedAs(Description)
-
describedAs
public SELF describedAs(Description description)
Description copied from class:AbstractAssertSets the description of the assertion that is going to be called after.You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
This overloaded version of "describedAs" offers more flexibility than the one taking a
Stringby allowing users to pass their own implementation of a description. For example, a description that creates its value lazily, only when an assertion failure occurs.- Specified by:
describedAsin interfaceDescriptable<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>>- Overrides:
describedAsin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
description- the new description to set.- Returns:
thisobject.
-
describedAs
public SELF describedAs(String description, Object... args)
Description copied from class:AbstractAssertSets the description of the assertion that is going to be called after.You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
Alias for
since "as" is a keyword in Groovy.Descriptable.as(String, Object...)- Specified by:
describedAsin interfaceDescriptable<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>>- Overrides:
describedAsin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
description- the new description to set.args- optional parameter if description is a format String.- Returns:
thisobject.
-
doesNotHave
public SELF doesNotHave(Condition<? super ACTUAL> condition)
Description copied from class:AbstractAssertVerifies that the actual value does not satisfy the given condition. This method is an alias for.ExtensionPoints.isNot(Condition)- Specified by:
doesNotHavein interfaceExtensionPoints<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
doesNotHavein classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
ExtensionPoints.isNot(Condition)
-
doesNotHaveSameClassAs
public SELF doesNotHaveSameClassAs(Object other)
Description copied from class:AbstractAssertVerifies that the actual value does not have the same class as the given object.Example:
// assertions will pass assertThat(1).doesNotHaveSameClassAs("abc"); assertThat(new ArrayList<String>()).doesNotHaveSameClassAs(new LinkedList<String>()); // assertions will fail assertThat(1).doesNotHaveSameClassAs(2); assertThat("abc").doesNotHaveSameClassAs("123"); assertThat(new ArrayList<String>()).doesNotHaveSameClassAs(new ArrayList<Integer>());- Specified by:
doesNotHaveSameClassAsin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
doesNotHaveSameClassAsin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
other- the object to check type against.- Returns:
- this assertion object.
-
has
public SELF has(Condition<? super ACTUAL> condition)
Description copied from class:AbstractAssertVerifies that the actual value satisfies the given condition. This method is an alias for.ExtensionPoints.is(Condition)- Specified by:
hasin interfaceExtensionPoints<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
hasin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
ExtensionPoints.is(Condition)
-
hasSameClassAs
public SELF hasSameClassAs(Object other)
Description copied from class:AbstractAssertVerifies that the actual value has the same class as the given object.Example:
// assertions will pass assertThat(1).hasSameClassAs(2); assertThat("abc").hasSameClassAs("123"); assertThat(new ArrayList<String>()).hasSameClassAs(new ArrayList<Integer>()); // assertions will fail assertThat(1).hasSameClassAs("abc"); assertThat(new ArrayList<String>()).hasSameClassAs(new LinkedList<String>());- Specified by:
hasSameClassAsin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
hasSameClassAsin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
other- the object to check type against.- Returns:
- this assertion object.
-
hasToString
public SELF hasToString(String expectedToString)
Description copied from class:AbstractAssertVerifies that actualactual.toString()is equal to the givenString.Example :
CartoonCharacter homer = new CartoonCharacter("Homer"); // Instead of writing ... assertThat(homer.toString()).isEqualTo("Homer"); // ... you can simply write: assertThat(homer).hasToString("Homer");- Specified by:
hasToStringin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
hasToStringin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
expectedToString- the expected String description of actual.- Returns:
- this assertion object.
-
is
public SELF is(Condition<? super ACTUAL> condition)
Description copied from class:AbstractAssertVerifies that the actual value satisfies the given condition. This method is an alias for.ExtensionPoints.has(Condition)- Specified by:
isin interfaceExtensionPoints<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
ExtensionPoints.has(Condition)
-
isEqualTo
public SELF isEqualTo(Object expected)
Description copied from class:AbstractAssertVerifies that the actual value is equal to the given one.Example:
// assertions will pass assertThat("abc").isEqualTo("abc"); assertThat(new HashMap<String, Integer>()).isEqualTo(new HashMap<String, Integer>()); // assertions will fail assertThat("abc").isEqualTo("123"); assertThat(new ArrayList<String>()).isEqualTo(1);- Specified by:
isEqualToin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isEqualToin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
expected- the given value to compare the actual value to.- Returns:
thisassertion object.
-
isExactlyInstanceOf
public SELF isExactlyInstanceOf(Class<?> type)
Description copied from class:AbstractAssertVerifies that the actual value is exactly an instance of the given type.Example:
// assertions will pass assertThat("abc").isExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isExactlyInstanceOf(ArrayList.class); assertThat(new HashMap<String, Integer>()).isExactlyInstanceOf(HashMap.class); // assertions will fail assertThat(1).isExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isExactlyInstanceOf(List.class); assertThat(new HashMap<String, Integer>()).isExactlyInstanceOf(Map.class);- Specified by:
isExactlyInstanceOfin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isExactlyInstanceOfin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isIn
public SELF isIn(Iterable<?> values)
Description copied from class:AbstractAssertVerifies that the actual value is present in the given values.Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass: assertThat(nenya).isIn(elvesRings); // assertion will fail: assertThat(oneRing).isIn(elvesRings);- Specified by:
isInin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isInin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given iterable to search the actual value in.- Returns:
thisassertion object.
-
isIn
public SELF isIn(Object... values)
Description copied from class:AbstractAssertVerifies that the actual value is present in the given array of values.Example:
Ring[] elvesRings = new Ring[] { vilya, nenya, narya }; // assertion will pass: assertThat(nenya).isIn(elvesRings); // assertion will fail: assertThat(oneRing).isIn(elvesRings);- Specified by:
isInin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isInin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given array to search the actual value in.- Returns:
thisassertion object.
-
isInstanceOf
public SELF isInstanceOf(Class<?> type)
Description copied from class:AbstractAssertVerifies that the actual value is an instance of the given type.Example:
// assertions will pass assertThat("abc").isInstanceOf(String.class); assertThat(new HashMap<String, Integer>()).isInstanceOf(HashMap.class); assertThat(new HashMap<String, Integer>()).isInstanceOf(Map.class); // assertions will fail assertThat(1).isInstanceOf(String.class); assertThat(new ArrayList<String>()).isInstanceOf(LinkedList.class);- Specified by:
isInstanceOfin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isInstanceOfin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isInstanceOfAny
public SELF isInstanceOfAny(Class<?>... types)
Description copied from class:AbstractAssertVerifies that the actual value is an instance of any of the given types.Example:
// assertions will pass assertThat("abc").isInstanceOfAny(String.class, Integer.class); assertThat(new ArrayList<String>()).isInstanceOfAny(LinkedList.class, ArrayList.class); assertThat(new HashMap<String, Integer>()).isInstanceOfAny(TreeMap.class, Map.class); // assertions will fail assertThat(1).isInstanceOfAny(Double.class, Float.class); assertThat(new ArrayList<String>()).isInstanceOfAny(LinkedList.class, Vector.class);- Specified by:
isInstanceOfAnyin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isInstanceOfAnyin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
types- the types to check the actual value against.- Returns:
- this assertion object.
-
isNot
public SELF isNot(Condition<? super ACTUAL> condition)
Description copied from class:AbstractAssertVerifies that the actual value does not satisfy the given condition. This method is an alias for.ExtensionPoints.doesNotHave(Condition)- Specified by:
isNotin interfaceExtensionPoints<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
ExtensionPoints.isNot(Condition)
-
isNotEqualTo
public SELF isNotEqualTo(Object other)
Description copied from class:AbstractAssertVerifies that the actual value is not equal to the given one.Example:
// assertions will pass assertThat("abc").isNotEqualTo("123"); assertThat(new ArrayList<String>()).isNotEqualTo(1); // assertions will fail assertThat("abc").isNotEqualTo("abc"); assertThat(new HashMap<String, Integer>()).isNotEqualTo(new HashMap<String, Integer>());- Specified by:
isNotEqualToin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotEqualToin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
other- the given value to compare the actual value to.- Returns:
thisassertion object.
-
isNotExactlyInstanceOf
public SELF isNotExactlyInstanceOf(Class<?> type)
Description copied from class:AbstractAssertVerifies that the actual value is not exactly an instance of given type.Example:
// assertions will pass assertThat(1).isNotExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isNotExactlyInstanceOf(List.class); assertThat(new HashMap<String, Integer>()).isNotExactlyInstanceOf(Map.class); // assertions will fail assertThat("abc").isNotExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isNotExactlyInstanceOf(ArrayList.class); assertThat(new HashMap<String, Integer>()).isNotExactlyInstanceOf(HashMap.class);- Specified by:
isNotExactlyInstanceOfin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotExactlyInstanceOfin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isNotIn
public SELF isNotIn(Iterable<?> values)
Description copied from class:AbstractAssertVerifies that the actual value is not present in the given values.Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass: assertThat(oneRing).isNotIn(elvesRings); // assertion will fail: assertThat(nenya).isNotIn(elvesRings);- Specified by:
isNotInin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotInin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given iterable to search the actual value in.- Returns:
thisassertion object.
-
isNotIn
public SELF isNotIn(Object... values)
Description copied from class:AbstractAssertVerifies that the actual value is not present in the given array of values.Example:
Ring[] elvesRings = new Ring[] { vilya, nenya, narya }; // assertion will pass: assertThat(oneRing).isNotIn(elvesRings); // assertion will fail: assertThat(nenya).isNotIn(elvesRings);- Specified by:
isNotInin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotInin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
values- the given array to search the actual value in.- Returns:
thisassertion object.
-
isNotInstanceOf
public SELF isNotInstanceOf(Class<?> type)
Description copied from class:AbstractAssertVerifies that the actual value is not an instance of the given type.Example:
// assertions will pass assertThat(1).isNotInstanceOf(Double.class); assertThat(new ArrayList<String>()).isNotInstanceOf(LinkedList.class); // assertions will fail assertThat("abc").isNotInstanceOf(String.class); assertThat(new HashMap<String, Integer>()).isNotInstanceOf(HashMap.class); assertThat(new HashMap<String, Integer>()).isNotInstanceOf(Map.class);- Specified by:
isNotInstanceOfin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotInstanceOfin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isNotInstanceOfAny
public SELF isNotInstanceOfAny(Class<?>... types)
Description copied from class:AbstractAssertVerifies that the actual value is not an instance of any of the given types.Example:
// assertions will pass assertThat(1).isNotInstanceOfAny(Double.class, Float.class); assertThat(new ArrayList<String>()).isNotInstanceOfAny(LinkedList.class, Vector.class); // assertions will fail assertThat(1).isNotInstanceOfAny(Double.class, Integer.class); assertThat(new ArrayList<String>()).isNotInstanceOfAny(LinkedList.class, ArrayList.class); assertThat(new HashMap<String, Integer>()).isNotInstanceOfAny(TreeMap.class, Map.class);- Specified by:
isNotInstanceOfAnyin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotInstanceOfAnyin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
types- the types to check the actual value against.- Returns:
- this assertion object.
-
isNotOfAnyClassIn
public SELF isNotOfAnyClassIn(Class<?>... types)
Description copied from class:AbstractAssertVerifies that the actual value type is not in given types.Example:
// assertions will pass assertThat(new HashMap<String, Integer>()).isNotOfAnyClassIn(Map.class, TreeMap.class); assertThat(new ArrayList<String>()).isNotOfAnyClassIn(LinkedList.class, List.class); // assertions will fail assertThat(new HashMap<String, Integer>()).isNotOfAnyClassIn(HashMap.class, TreeMap.class); assertThat(new ArrayList<String>()).isNotOfAnyClassIn(ArrayList.class, LinkedList.class);- Specified by:
isNotOfAnyClassInin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotOfAnyClassInin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
types- the types to check the actual value against.- Returns:
- this assertion object.
-
isNotNull
public SELF isNotNull()
Description copied from class:AbstractAssertVerifies that the actual value is notnull.Example:
// assertion will pass assertThat("abc").isNotNull(); assertThat(new HashMap<String, Integer>()).isNotNull(); // assertion will fail String value = null; assertThat(value).isNotNull();- Specified by:
isNotNullin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotNullin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
isNotSameAs
public SELF isNotSameAs(Object other)
Description copied from class:AbstractAssertVerifies that the actual value is not the same as the given one, ie using == comparison.Example:
// Name is a class with first and last fields, two Names are equals if both first and last are equals. Name tyrion = new Name("Tyrion", "Lannister"); Name alias = tyrion; Name clone = new Name("Tyrion", "Lannister"); // assertions succeed: assertThat(clone).isNotSameAs(tyrion) .isEqualTo(tyrion); // assertion fails: assertThat(alias).isNotSameAs(tyrion);- Specified by:
isNotSameAsin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isNotSameAsin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
other- the given value to compare the actual value to.- Returns:
thisassertion object.
-
isOfAnyClassIn
public SELF isOfAnyClassIn(Class<?>... types)
Description copied from class:AbstractAssertVerifies that the actual value type is in given types.Example:
// assertions will pass assertThat(new HashMap<String, Integer>()).isOfAnyClassIn(HashMap.class, TreeMap.class); assertThat(new ArrayList<String>()).isOfAnyClassIn(ArrayList.class, LinkedList.class); // assertions will fail assertThat(new HashMap<String, Integer>()).isOfAnyClassIn(TreeMap.class, Map.class); assertThat(new ArrayList<String>()).isOfAnyClassIn(LinkedList.class, List.class);- Specified by:
isOfAnyClassInin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isOfAnyClassInin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
types- the types to check the actual value against.- Returns:
- this assertion object.
-
isSameAs
public SELF isSameAs(Object expected)
Description copied from class:AbstractAssertVerifies that the actual value is the same as the given one, ie using == comparison.Example:
// Name is a class with first and last fields, two Names are equals if both first and last are equals. Name tyrion = new Name("Tyrion", "Lannister"); Name alias = tyrion; Name clone = new Name("Tyrion", "Lannister"); // assertions succeed: assertThat(tyrion).isSameAs(alias) .isEqualTo(clone); // assertion fails: assertThat(tyrion).isSameAs(clone);- Specified by:
isSameAsin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
isSameAsin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
expected- the given value to compare the actual value to.- Returns:
thisassertion object.
-
noneMatch
public SELF noneMatch(Predicate<? super ELEMENT> predicate)
Description copied from interface:ObjectEnumerableAssertVerifies that no elements match the givenPredicate.Example :
Note that you can achieve the same result withIterable<String> abcc = newArrayList("a", "b", "cc"); // assertion will pass assertThat(abcc).noneMatch(s -> s.isEmpty()); // assertion will fail assertThat(abcc).noneMatch(s -> s.length() == 2);areNot(Condition)ordoNotHave(Condition).- Specified by:
noneMatchin interfaceObjectEnumerableAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
predicate- the givenPredicate.- Returns:
thisobject.
-
overridingErrorMessage
public SELF overridingErrorMessage(String newErrorMessage, Object... args)
Description copied from class:AbstractAssertOverrides AssertJ default error message by the given one.You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
The new error message is built using
String.format(String, Object...)if you provide args parameter (if you don't, the error message is taken as it is).Example :
assertThat(player.isRookie()).overridingErrorMessage("Expecting Player <%s> to be a rookie but was not.", player) .isTrue();- Overrides:
overridingErrorMessagein classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
newErrorMessage- the error message that will replace the default one provided by Assertj.args- the args used to fill error message as inString.format(String, Object...).- Returns:
- this assertion object.
-
usingDefaultComparator
public SELF usingDefaultComparator()
Description copied from class:AbstractAssertRevert to standard comparison for the incoming assertion checks.This method should be used to disable a custom comparison strategy set by calling
usingComparator.- Specified by:
usingDefaultComparatorin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
usingDefaultComparatorin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
thisassertion object.
-
usingComparator
public SELF usingComparator(Comparator<? super ACTUAL> customComparator)
Description copied from class:AbstractAssertUse the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.The custom comparator is bound to assertion instance, meaning that if a new assertion instance is created, the default comparison strategy will be used.
Examples :
// frodo and sam are instances of Character with Hobbit race (obviously :). // raceComparator implements Comparator<Character> assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam);- Specified by:
usingComparatorin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
usingComparatorin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
customComparator- the comparator to use for the incoming assertion checks.- Returns:
thisassertion object.
-
usingComparator
public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription)
Description copied from class:AbstractAssertUse the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.The custom comparator is bound to assertion instance, meaning that if a new assertion instance is created, the default comparison strategy will be used.
Examples :
// frodo and sam are instances of Character with Hobbit race (obviously :). // raceComparator implements Comparator<Character> assertThat(frodo).usingComparator(raceComparator, "Hobbit Race Comparator").isEqualTo(sam);- Specified by:
usingComparatorin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
usingComparatorin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
customComparator- the comparator to use for the incoming assertion checks.customComparatorDescription- comparator description to be used in assertion error messages- Returns:
thisassertion object.
-
withFailMessage
public SELF withFailMessage(String newErrorMessage, Object... args)
Description copied from class:AbstractAssertAlternative method forAbstractAssert.overridingErrorMessage(java.lang.String, java.lang.Object...)You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
Example:
assertThat(player.isRookie()).withFailMessage("Expecting Player <%s> to be a rookie but was not.", player) .isTrue();- Overrides:
withFailMessagein classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Parameters:
newErrorMessage- the error message that will replace the default one provided by Assertj.args- the args used to fill error message as inString.format(String, Object...).- Returns:
- this assertion object.
-
withThreadDumpOnError
public SELF withThreadDumpOnError()
Description copied from class:AbstractAssertIn case of an assertion error, a thread dump will be printed toSystem.err.Example :
will print a thread dump, something similar to this:assertThat("Messi").withThreadDumpOnError().isEqualTo("Ronaldo");"JDWP Command Reader" java.lang.Thread.State: RUNNABLE "JDWP Event Helper Thread" java.lang.Thread.State: RUNNABLE "JDWP Transport Listener: dt_socket" java.lang.Thread.State: RUNNABLE "Signal Dispatcher" java.lang.Thread.State: RUNNABLE "Finalizer" java.lang.Thread.State: WAITING at java.lang.Object.wait(Native Method) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:189) "Reference Handler" java.lang.Thread.State: WAITING at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:503) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133) "main" java.lang.Thread.State: RUNNABLE at sun.management.ThreadImpl.dumpThreads0(Native Method) at sun.management.ThreadImpl.dumpAllThreads(ThreadImpl.java:446) at org.assertj.core.internal.Failures.threadDumpDescription(Failures.java:193) at org.assertj.core.internal.Failures.printThreadDumpIfNeeded(Failures.java:141) at org.assertj.core.internal.Failures.failure(Failures.java:91) at org.assertj.core.internal.Objects.assertEqual(Objects.java:314) at org.assertj.core.api.AbstractAssert.isEqualTo(AbstractAssert.java:198) at org.assertj.examples.ThreadDumpOnErrorExample.main(ThreadDumpOnErrorExample.java:28)- Specified by:
withThreadDumpOnErrorin interfaceAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Overrides:
withThreadDumpOnErrorin classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>- Returns:
- this assertion object.
-
size
public AbstractIterableSizeAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT> size()
Returns anAssertobject that allows performing assertions on the size of theIterableunder test.Once this method is called, the object under test is no longer the
Iterablebut its size, to perform assertions on theIterable, callAbstractIterableSizeAssert.returnToIterable().Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass: assertThat(elvesRings).size().isGreaterThan(1) .isLessThanOrEqualTo(3) .returnToIterable().contains(narya) .doesNotContain(oneRing); // assertion will fail: assertThat(elvesRings).size().isGreaterThan(3);- Returns:
- AbstractIterableSizeAssert built with the
Iterable's size. - Throws:
NullPointerException- if the givenIterableisnull.
-
getComparatorsByType
protected TypeComparators getComparatorsByType()
-
getComparatorsForElementPropertyOrFieldTypes
protected TypeComparators getComparatorsForElementPropertyOrFieldTypes()
-
newAbstractIterableAssert
protected abstract SELF newAbstractIterableAssert(Iterable<? extends ELEMENT> iterable)
-
withAssertionState
SELF withAssertionState(AbstractAssert assertInstance)
- Overrides:
withAssertionStatein classAbstractAssert<SELF extends AbstractIterableAssert<SELF,ACTUAL,ELEMENT,ELEMENT_ASSERT>,ACTUAL extends Iterable<? extends ELEMENT>>
-
withTypeComparators
SELF withTypeComparators(TypeComparators comparatorsByType)
-
withComparatorsForElementPropertyOrFieldNames
SELF withComparatorsForElementPropertyOrFieldNames(Map<String,Comparator<?>> comparatorsForElementPropertyOrFieldNames)
-
withComparatorsForElementPropertyOrFieldTypes
SELF withComparatorsForElementPropertyOrFieldTypes(TypeComparators comparatorsForElementPropertyOrFieldTypes)
-
-