Interface WithAssertions
-
- All Superinterfaces:
InstanceOfAssertFactories
public interface WithAssertions extends InstanceOfAssertFactories
A unified entry point to all non-deprecated assertions from both the new Java 8 core API and the pre-Java 8 core API. As a convenience, the methods are defined in an interface so that no static imports are necessary if the test class implements this interface. Based on an idea by David Gageot : http://blog.javabien.net/2014/04/23/what-if-assertj-used-java-8/- Author:
- Alan Rothkopf
-
-
Field Summary
-
Fields inherited from interface org.assertj.core.api.InstanceOfAssertFactories
ARRAY, ATOMIC_BOOLEAN, ATOMIC_INTEGER, ATOMIC_INTEGER_ARRAY, ATOMIC_INTEGER_FIELD_UPDATER, ATOMIC_LONG, ATOMIC_LONG_ARRAY, ATOMIC_LONG_FIELD_UPDATER, ATOMIC_MARKABLE_REFERENCE, ATOMIC_REFERENCE, ATOMIC_REFERENCE_ARRAY, ATOMIC_REFERENCE_FIELD_UPDATER, ATOMIC_STAMPED_REFERENCE, BIG_DECIMAL, BIG_INTEGER, BOOLEAN, BOOLEAN_ARRAY, BYTE, BYTE_ARRAY, CHAR_ARRAY, CHAR_SEQUENCE, CHARACTER, CLASS, COMPLETABLE_FUTURE, COMPLETION_STAGE, DATE, DOUBLE, DOUBLE_ARRAY, DOUBLE_PREDICATE, DOUBLE_STREAM, FILE, FLOAT, FLOAT_ARRAY, FUTURE, INPUT_STREAM, INSTANT, INT_ARRAY, INT_PREDICATE, INT_STREAM, INTEGER, ITERABLE, ITERATOR, LIST, LOCAL_DATE, LOCAL_DATE_TIME, LOCAL_TIME, LONG, LONG_ARRAY, LONG_PREDICATE, LONG_STREAM, MAP, OFFSET_DATE_TIME, OFFSET_TIME, OPTIONAL, OPTIONAL_DOUBLE, OPTIONAL_INT, OPTIONAL_LONG, PATH, PREDICATE, SHORT, SHORT_ARRAY, STREAM, STRING, STRING_BUFFER, STRING_BUILDER, THROWABLE, URI_TYPE, URL_TYPE, ZONED_DATE_TIME
-
-
Method Summary
All Methods Instance Methods Default Methods Modifier and Type Method Description default <T> Condition<T>allOf(Iterable<? extends Condition<? super T>> conditions)Creates a newAllOfdefault <T> Condition<T>allOf(Condition<? super T>... conditions)Creates a newAllOfdefault <T> Condition<T>anyOf(Iterable<? extends Condition<? super T>> conditions)Creates a newAnyOfdefault <T> Condition<T>anyOf(Condition<? super T>... conditions)Only delegate toAnyOf.anyOf(Condition...)so that Assertions offers a full feature entry point to all AssertJ features (but you can useAnyOfif you prefer).default AbstractBooleanAssert<?>assertThat(boolean actual)Creates a new instance of.BooleanAssertdefault AbstractBooleanArrayAssert<?>assertThat(boolean[] actual)Creates a new instance of.BooleanArrayAssertdefault AbstractByteAssert<?>assertThat(byte actual)Creates a new instance of.ByteAssertdefault AbstractByteArrayAssert<?>assertThat(byte[] actual)Creates a new instance of.ByteArrayAssertdefault AbstractCharacterAssert<?>assertThat(char actual)Creates a new instance of.CharacterAssertdefault AbstractCharArrayAssert<?>assertThat(char[] actual)Creates a new instance of.CharArrayAssertdefault AbstractDoubleAssert<?>assertThat(double actual)Creates a new instance of.DoubleAssertdefault AbstractDoubleArrayAssert<?>assertThat(double[] actual)Creates a new instance of.DoubleArrayAssertdefault AbstractFloatAssert<?>assertThat(float actual)Creates a new instance of.FloatAssertdefault AbstractFloatArrayAssert<?>assertThat(float[] actual)Creates a new instance of.FloatArrayAssertdefault AbstractIntegerAssert<?>assertThat(int actual)Creates a new instance of.IntegerAssertdefault AbstractIntArrayAssert<?>assertThat(int[] actual)Creates a new instance of.IntArrayAssertdefault AbstractLongAssert<?>assertThat(long actual)Creates a new instance of.LongAssertdefault AbstractLongArrayAssert<?>assertThat(long[] actual)Creates a new instance of.LongArrayAssertdefault AbstractShortAssert<?>assertThat(short actual)Creates a new instance of.ShortAssertdefault AbstractShortArrayAssert<?>assertThat(short[] actual)Creates a new instance of.ShortArrayAssertdefault <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
ClassBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT>assertThat(ACTUAL actual, Class<ELEMENT_ASSERT> assertClass)Creates a new instance ofallowing to navigate to anyClassBasedNavigableIterableAssertIterableelement in order to perform assertions on it.default AbstractFileAssert<?>assertThat(File actual)Creates a new instance of.FileAssertdefault AbstractInputStreamAssert<?,? extends InputStream>assertThat(InputStream actual)Creates a new instance of.InputStreamAssertdefault AbstractBooleanAssert<?>assertThat(Boolean actual)Creates a new instance of.BooleanAssertdefault AbstractByteAssert<?>assertThat(Byte actual)Creates a new instance of.ByteAssertdefault AbstractCharacterAssert<?>assertThat(Character actual)Creates a new instance of.CharacterAssertdefault AbstractCharSequenceAssert<?,? extends CharSequence>assertThat(CharSequence actual)Creates a new instance of.CharSequenceAssertdefault ClassAssertassertThat(Class<?> actual)Creates a new instance ofClassAssertdefault AbstractDoubleAssert<?>assertThat(Double actual)Creates a new instance of.DoubleAssertdefault AbstractFloatAssert<?>assertThat(Float actual)Creates a new instance of.FloatAssertdefault AbstractIntegerAssert<?>assertThat(Integer actual)Creates a new instance of.IntegerAssertdefault <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
FactoryBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT>assertThat(Iterable<? extends ELEMENT> actual, AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)Creates a new instance ofallowing to navigate to anyFactoryBasedNavigableIterableAssertIterableelement in order to perform assertions on it.default <T> IterableAssert<T>assertThat(Iterable<? extends T> actual)Creates a new instance of.IterableAssertdefault AbstractLongAssert<?>assertThat(Long actual)Creates a new instance of.LongAssertdefault AbstractShortAssert<?>assertThat(Short actual)Creates a new instance of.ShortAssertdefault AbstractStringAssert<?>assertThat(String actual)Creates a new instance of.CharSequenceAssertfrom aStringdefault AbstractCharSequenceAssert<?,? extends CharSequence>assertThat(StringBuffer actual)Creates a new instance offrom aCharSequenceAssertStringBuffer.default AbstractCharSequenceAssert<?,? extends CharSequence>assertThat(StringBuilder actual)Creates a new instance offrom aCharSequenceAssertStringBuilder.default AbstractThrowableAssert<?,? extends Throwable>assertThat(Throwable actual)Creates a new instance of.ThrowableAssertdefault AbstractBigDecimalAssert<?>assertThat(BigDecimal actual)Creates a new instance of.BigDecimalAssertdefault AbstractBigIntegerAssert<?>assertThat(BigInteger actual)Creates a new instance of.BigIntegerAssertdefault AbstractUriAssert<?>assertThat(URI actual)Creates a new instance of.UriAssertdefault AbstractUrlAssert<?>assertThat(URL actual)Creates a new instance of.UrlAssertdefault AbstractPathAssert<?>assertThat(Path actual)Creates a new instance ofPathAssertdefault AbstractInstantAssert<?>assertThat(Instant actual)Creates a new instance of.InstantAssertdefault AbstractLocalDateAssert<?>assertThat(LocalDate localDate)Creates a new instance of.LocalDateAssertdefault AbstractLocalDateTimeAssert<?>assertThat(LocalDateTime localDateTime)Creates a new instance of.LocalDateTimeAssertdefault AbstractLocalTimeAssert<?>assertThat(LocalTime localTime)Creates a new instance of.LocalTimeAssertdefault AbstractOffsetDateTimeAssert<?>assertThat(OffsetDateTime offsetDateTime)Creates a new instance of.OffsetTimeAssertdefault AbstractOffsetTimeAssert<?>assertThat(OffsetTime offsetTime)Creates a new instance of.OffsetTimeAssertdefault AbstractZonedDateTimeAssert<?>assertThat(ZonedDateTime actual)Creates a new instance of.ZonedDateTimeAssertdefault AtomicBooleanAssertassertThat(AtomicBoolean actual)Create assertion forAtomicBoolean.default AtomicIntegerAssertassertThat(AtomicInteger actual)Create assertion forAtomicInteger.default AtomicIntegerArrayAssertassertThat(AtomicIntegerArray actual)Create int[] assertion forAtomicIntegerArray.default <OBJECT> AtomicIntegerFieldUpdaterAssert<OBJECT>assertThat(AtomicIntegerFieldUpdater<OBJECT> actual)Create assertion forAtomicIntegerFieldUpdater.default AtomicLongAssertassertThat(AtomicLong actual)Create assertion forAtomicLong.default AtomicLongArrayAssertassertThat(AtomicLongArray actual)Create assertion forAtomicLongArray.default <OBJECT> AtomicLongFieldUpdaterAssert<OBJECT>assertThat(AtomicLongFieldUpdater<OBJECT> actual)Create assertion forAtomicLongFieldUpdater.default <VALUE> AtomicMarkableReferenceAssert<VALUE>assertThat(AtomicMarkableReference<VALUE> actual)Create assertion forAtomicMarkableReference.default <VALUE> AtomicReferenceAssert<VALUE>assertThat(AtomicReference<VALUE> actual)Create assertion forAtomicReference.default <ELEMENT> AtomicReferenceArrayAssert<ELEMENT>assertThat(AtomicReferenceArray<ELEMENT> actual)Create assertion forAtomicReferenceArray.default <FIELD,OBJECT>
AtomicReferenceFieldUpdaterAssert<FIELD,OBJECT>assertThat(AtomicReferenceFieldUpdater<OBJECT,FIELD> actual)Create assertion forAtomicReferenceFieldUpdater.default <VALUE> AtomicStampedReferenceAssert<VALUE>assertThat(AtomicStampedReference<VALUE> actual)Create assertion forAtomicStampedReference.default <RESULT> CompletableFutureAssert<RESULT>assertThat(CompletableFuture<RESULT> future)Create assertion forCompletableFuture.default <RESULT> CompletableFutureAssert<RESULT>assertThat(CompletionStage<RESULT> completionStage)Create assertion forCompletionStageby converting it to aCompletableFutureand returning aCompletableFutureAssert.default <RESULT> FutureAssert<RESULT>assertThat(Future<RESULT> actual)Create assertion forFuture.default AbstractDateAssert<?>assertThat(Date actual)Creates a new instance of.DateAssertdefault DoublePredicateAssertassertThat(DoublePredicate actual)Create assertion forDoublePredicate.default IntPredicateAssertassertThat(IntPredicate actual)Create assertion forIntPredicate.default LongPredicateAssertassertThat(LongPredicate actual)Create assertion forLongPredicate.default <T> PredicateAssert<T>assertThat(Predicate<T> actual)Create assertion forPredicate.default <T> IteratorAssert<T>assertThat(Iterator<? extends T> actual)Creates a new instance of.IteratorAssertdefault <ELEMENT,ACTUAL extends List<? extends ELEMENT>,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
ClassBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT>assertThat(List<? extends ELEMENT> actual, Class<ELEMENT_ASSERT> assertClass)Creates a new instance oftallowing to navigate to anyClassBasedNavigableListAssertListelement in order to perform assertions on it.default <ACTUAL extends List<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
FactoryBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT>assertThat(List<? extends ELEMENT> actual, AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)Creates a new instance ofallowing to navigate to anyFactoryBasedNavigableListAssertListelement in order to perform assertions on it.default <T> ListAssert<T>assertThat(List<? extends T> actual)Creates a new instance of.ListAssertdefault <K,V>
MapAssert<K,V>assertThat(Map<K,V> actual)Creates a new instance of.MapAssertdefault <VALUE> OptionalAssert<VALUE>assertThat(Optional<VALUE> optional)Create assertion forOptional.default OptionalDoubleAssertassertThat(OptionalDouble optional)Create assertion forOptionalDouble.default OptionalIntAssertassertThat(OptionalInt optional)Create assertion forOptionalInt.default OptionalLongAssertassertThat(OptionalLong optional)Create assertion forOptionalLong.default ListAssert<Double>assertThat(DoubleStream actual)Creates a new instance offrom the givenListAssertDoubleStream.default ListAssert<Integer>assertThat(IntStream actual)Creates a new instance offrom the givenListAssertIntStream.default ListAssert<Long>assertThat(LongStream actual)Creates a new instance offrom the givenListAssertLongStream.default <ELEMENT> ListAssert<ELEMENT>assertThat(Stream<? extends ELEMENT> actual)Creates a new instance offrom the givenListAssertStream.default <T> TassertThat(AssertProvider<T> component)Delegates the creation of theAssertto theAssertProvider.assertThat()of the given component.default <T extends AssertDelegateTarget>
TassertThat(T assertion)Returns the given assertion.default <T> ObjectArrayAssert<T>assertThat(T[] actual)Creates a new instance of.ObjectArrayAssertdefault AbstractThrowableAssert<?,? extends Throwable>assertThatCode(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable)Allows to capture and then assert on aThrowablemore easily when used with Java 8 lambdas.default <T extends Throwable>
ThrowableTypeAssert<T>assertThatExceptionOfType(Class<? extends T> exceptionType)Entry point to check that an exception of type T is thrown by a giventhrowingCallablewhich allows to chain assertions on the thrown exception.default ThrowableTypeAssert<IllegalArgumentException>assertThatIllegalArgumentException()Alias forassertThatExceptionOfType(Class)forIllegalArgumentException.default ThrowableTypeAssert<IllegalStateException>assertThatIllegalStateException()Alias forassertThatExceptionOfType(Class)forIllegalStateException.default ThrowableTypeAssert<IOException>assertThatIOException()Alias forassertThatExceptionOfType(Class)forIOException.default ThrowableTypeAssert<NullPointerException>assertThatNullPointerException()Alias forassertThatExceptionOfType(Class)forNullPointerException.default <T> ObjectAssert<T>assertThatObject(T actual)Creates a new instance offor any object.ObjectAssertdefault AbstractThrowableAssert<?,? extends Throwable>assertThatThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)Allows to capture and then assert on aThrowable(easier done with lambdas).default AbstractThrowableAssert<?,? extends Throwable>assertThatThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, String description, Object... args)Allows to capture and then assert on aThrowablelikeassertThatThrownBy(ThrowingCallable)but this method let you set the assertion description the same way you do withas(String, Object...).default IndexatIndex(int index)Only delegate toIndex.atIndex(int)so that Assertions offers a full feature entry point to all AssertJ features (but you can useIndexif you prefer).default TemporalUnitOffsetbyLessThan(long value, TemporalUnit unit)Assertions entry point forTemporalUnitOffsetwith strict less than condition to use withisCloseTotemporal assertions.default Offset<Byte>byLessThan(Byte value)Assertions entry point for ByteOffsetto use with isCloseTo assertions.default Offset<Double>byLessThan(Double value)Alias foroffset(Double)to use with isCloseTo assertions.default Offset<Float>byLessThan(Float value)Alias foroffset(Float)to use with isCloseTo assertions.default Offset<Integer>byLessThan(Integer value)Assertions entry point for IntegerOffsetto use with isCloseTo assertions.default Offset<Long>byLessThan(Long value)Assertions entry point for LongOffsetto use with isCloseTo assertions.default Offset<Short>byLessThan(Short value)Assertions entry point for ShortOffsetto use with isCloseTo assertions.default Offset<BigDecimal>byLessThan(BigDecimal value)Assertions entry point for BigDecimalOffsetto use with isCloseTo assertions.default Offset<BigInteger>byLessThan(BigInteger value)Assertions entry point for BigIntegerOffsetto use with isCloseTo assertions.default ThrowablecatchThrowable(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)Allows to catch anThrowablemore easily when used with Java 8 lambdas.default <THROWABLE extends Throwable>
THROWABLEcatchThrowableOfType(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, Class<THROWABLE> type)Allows catching aThrowableof a specific type.default StringcontentOf(File file)Loads the text content of a file with the default character set, so that it can be passed toassertThat(String).default StringcontentOf(File file, String charsetName)Loads the text content of a file, so that it can be passed toassertThat(String).default StringcontentOf(File file, Charset charset)Loads the text content of a file, so that it can be passed toassertThat(String).default StringcontentOf(URL url)Loads the text content of a URL with the default character set, so that it can be passed toassertThat(String).default StringcontentOf(URL url, String charsetName)Loads the text content of a URL, so that it can be passed toassertThat(String).default StringcontentOf(URL url, Charset charset)Loads the text content of a URL, so that it can be passed toassertThat(String).default <T> DoesNotHave<T>doesNotHave(Condition<? super T> condition)Creates a new.DoesNotHavedefault <K,V>
MapEntry<K,V>entry(K key, V value)Only delegate toMapEntry.entry(Object, Object)so that Assertions offers a full feature entry point to all AssertJ features (but you can useMapEntryif you prefer).default Properties<Object>extractProperty(String propertyName)Only delegate toProperties.extractProperty(String)so that Assertions offers a full feature entry point to all AssertJ features (but you can usePropertiesif you prefer).default <T> Properties<T>extractProperty(String propertyName, Class<T> propertyType)Only delegate toProperties.extractProperty(String)so that Assertions offers a full feature entry point to all AssertJ features (but you can usePropertiesif you prefer).default <T> Tfail(String failureMessage)Throws anAssertionErrorwith the given message.default <T> Tfail(String failureMessage, Object... args)Throws anAssertionErrorwith the given message built asString.format(String, Object...).default <T> Tfail(String failureMessage, Throwable realCause)Throws anAssertionErrorwith the given message and with theThrowablethat caused the failure.default <T> TfailBecauseExceptionWasNotThrown(Class<? extends Throwable> throwableClass)Throws anAssertionErrorwith a message explaining that aThrowableof given class was expected to be thrown but had not been.default <E> Filters<E>filter(E[] array)Only delegate toFilters.filter(Object[])so that Assertions offers a full feature entry point to all AssertJ features (but you can useFiltersif you prefer).default <E> Filters<E>filter(Iterable<E> iterableToFilter)Only delegate toFilters.filter(Object[])so that Assertions offers a full feature entry point to all AssertJ features (but you can useFiltersif you prefer).default <F,T>
Function<F,T>from(Function<F,T> extractor)A syntax sugar to write fluent assertion usingAbstractObjectAssert.returns(Object, Function).default InFilterin(Object... values)Create aFilterOperatorto use infilteredOn(String, FilterOperation)to express a filter keeping all Iterable elements whose property/field value matches one of the given values.default List<String>linesOf(File file)Loads the text content of a file into a list of strings with the default charset, each string corresponding to a line.default List<String>linesOf(File file, String charsetName)Loads the text content of a file into a list of strings, each string corresponding to a line.default List<String>linesOf(File file, Charset charset)Loads the text content of a file into a list of strings, each string corresponding to a line.default List<String>linesOf(URL url)Loads the text content of a URL into a list of strings with the default charset, each string corresponding to a line.default List<String>linesOf(URL url, String charsetName)Loads the text content of a URL into a list of strings, each string corresponding to a line.default List<String>linesOf(URL url, Charset charset)Loads the text content of a URL into a list of strings, each string corresponding to a line.default NotFilternot(Object valueNotToMatch)Create aFilterOperatorto use infilteredOn(String, FilterOperation)to express a filter keeping all Iterable elements whose property/field value matches does not match the given value.default <T> Not<T>not(Condition<? super T> condition)Creates a new.Notdefault NotInFilternotIn(Object... valuesNotToMatch)Create aFilterOperatorto use infilteredOn(String, FilterOperation)to express a filter keeping all Iterable elements whose property/field value matches does not match any of the given values.default Offset<Double>offset(Double value)Assertions entry point for doubleOffset.default Offset<Float>offset(Float value)Assertions entry point for floatOffset.default voidregisterCustomDateFormat(String userCustomDateFormatPattern)Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String).default voidregisterCustomDateFormat(DateFormat userCustomDateFormat)Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String).default <T> voidregisterFormatterForType(Class<T> type, Function<T,String> formatter)Assertions error messages uses aRepresentationto format the different types involved, using this method you can control the formatting of a given type by providing a specific formatter.default voidsetAllowComparingPrivateFields(boolean allowComparingPrivateFields)Globally sets whether the use of private fields is allowed for comparison.default voidsetAllowExtractingPrivateFields(boolean allowExtractingPrivateFields)Globally sets whetherandIterableAssert#extracting(String)should be allowed to extract private fields, if not and they try it fails with exception.ObjectArrayAssert#extracting(String)default voidsetExtractBareNamePropertyMethods(boolean barenamePropertyMethods)Globally sets whether the extractor considers bare-named property methods likeString name().default voidsetLenientDateParsing(boolean value)Instead of using default strict date/time parsing, it is possible to use lenient parsing mode for default date formats parser to interpret inputs that do not precisely match supported date formats (lenient parsing).default voidsetMaxElementsForPrinting(int maxElementsForPrinting)In error messages, sets the threshold for how many elements from one iterable/array/map will be included in the in the description.default voidsetMaxLengthForSingleLineDescription(int maxLengthForSingleLineDescription)In error messages, sets the threshold when iterable/array formatting will on one line (if their String description is less than this parameter) or it will be formatted with one element per line.default voidsetRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace)Sets whether we remove elements related to AssertJ from assertion error stack trace.default <T> TshouldHaveThrown(Class<? extends Throwable> throwableClass)Throws anAssertionErrorwith a message explaining that aThrowableof given class was expected to be thrown but had not been.default Tupletuple(Object... values)Utility method to build nicely aTuplewhen working withAbstractIterableAssert.extracting(String...)orAbstractObjectArrayAssert.extracting(String...)default voiduseDefaultDateFormatsOnly()Remove all registered custom date formats => use only the defaults date formats to parse string as date.default voiduseDefaultRepresentation()Fallback to useStandardRepresentationto revert the effect of callinguseRepresentation(Representation).default voiduseRepresentation(Representation customRepresentation)Register aRepresentationthat will be used in all following assertions.default TemporalUnitOffsetwithin(long value, TemporalUnit unit)Assertions entry point forTemporalUnitOffsetwith with less than or equal condition to use with isCloseTo temporal assertions.default Offset<Byte>within(Byte value)Assertions entry point for ByteOffsetto use with isCloseTo assertions.default Offset<Double>within(Double value)Alias foroffset(Double)to use with isCloseTo assertions.default Offset<Float>within(Float value)Alias foroffset(Float)to use with isCloseTo assertions.default Offset<Integer>within(Integer value)Assertions entry point for IntegerOffsetto use with isCloseTo assertions.default Offset<Long>within(Long value)Assertions entry point for LongOffsetto use with isCloseTo assertions.default Offset<Short>within(Short value)Assertions entry point for ShortOffsetto use with isCloseTo assertions.default Offset<BigDecimal>within(BigDecimal value)Assertions entry point for BigDecimalOffsetto use with isCloseTo assertions.default Offset<BigInteger>within(BigInteger value)Assertions entry point for BigIntegerOffsetto use with isCloseTo assertions.default PercentagewithinPercentage(Double value)Assertions entry point for DoublePercentageto use with isCloseTo assertions for percentages.default PercentagewithinPercentage(Integer value)Assertions entry point for IntegerPercentageto use with isCloseTo assertions for percentages.default PercentagewithinPercentage(Long value)Assertions entry point for LongPercentageto use with isCloseTo assertions for percentages.default Offset<Double>withPrecision(Double value)Assertions entry point for doubleOffset.default Offset<Float>withPrecision(Float value)Assertions entry point for floatOffset.
-
-
-
Method Detail
-
offset
default Offset<Float> offset(Float value)
Assertions entry point for floatOffset.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, offset(0.2f));- Parameters:
value- the allowed offset- Returns:
- the created
Offset.
-
offset
default Offset<Double> offset(Double value)
Assertions entry point for doubleOffset.Typical usage :
assertThat(8.1).isEqualTo(8.0, offset(0.1));- Parameters:
value- the allowed offset- Returns:
- the created
Offset.
-
entry
default <K,V> MapEntry<K,V> entry(K key, V value)
Only delegate toMapEntry.entry(Object, Object)so that Assertions offers a full feature entry point to all AssertJ features (but you can useMapEntryif you prefer).Typical usage is to call
entryin MapAssertcontainsassertion, see examples below :Map<Ring, TolkienCharacter> ringBearers = ... // init omitted assertThat(ringBearers).contains(entry(oneRing, frodo), entry(nenya, galadriel));- Type Parameters:
K- the type of keys in the map.V- the type of values in the map.- Parameters:
key- the key of the entry to create.value- the value of the entry to create.- Returns:
- the created
MapEntry.
-
fail
default <T> T fail(String failureMessage)
Throws anAssertionErrorwith the given message.- Type Parameters:
T- dummy return value type- Parameters:
failureMessage- error message.- Returns:
- nothing, it's just to be used in doSomething(optional.orElse(() -> fail("boom")));.
- Throws:
AssertionError- with the given message.
-
fail
default <T> T fail(String failureMessage, Object... args)
Throws anAssertionErrorwith the given message built asString.format(String, Object...).- Type Parameters:
T- dummy return value type- Parameters:
failureMessage- error message.args- Arguments referenced by the format specifiers in the format string.- Returns:
- nothing, it's just to be used in doSomething(optional.orElse(() -> fail("b%s", ""oom)));.
- Throws:
AssertionError- with the given built message.- Since:
- 3.9.0
-
fail
default <T> T fail(String failureMessage, Throwable realCause)
Throws anAssertionErrorwith the given message and with theThrowablethat caused the failure.- Type Parameters:
T- dummy return value type- Parameters:
failureMessage- the description of the failed assertion. It can benull.realCause- cause of the error.- Returns:
- nothing, it's just to be used in doSomething(optional.orElse(() -> fail("boom", cause)));.
- Throws:
AssertionError- with the given message and with theThrowablethat caused the failure.
-
not
default <T> Not<T> not(Condition<? super T> condition)
Creates a new.Not- Type Parameters:
T- the type of object the given condition accept.- Parameters:
condition- the condition to inverse.- Returns:
- The Not condition created.
-
allOf
default <T> Condition<T> allOf(Iterable<? extends Condition<? super T>> conditions)
Creates a newAllOf- Type Parameters:
T- the type of object the given condition accept.- Parameters:
conditions- the conditions to evaluate.- Returns:
- the created
AllOf. - Throws:
NullPointerException- if the given iterable isnull.NullPointerException- if any of the elements in the given iterable isnull.
-
allOf
default <T> Condition<T> allOf(Condition<? super T>... conditions)
Creates a newAllOf- Type Parameters:
T- the type of object the given condition accept.- Parameters:
conditions- the conditions to evaluate.- Returns:
- the created
AllOf. - Throws:
NullPointerException- if the given array isnull.NullPointerException- if any of the elements in the given array isnull.
-
assertThat
default <T> ObjectArrayAssert<T> assertThat(T[] actual)
Creates a new instance of.ObjectArrayAssert- Type Parameters:
T- the actual's elements type.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <T extends AssertDelegateTarget> T assertThat(T assertion)
Returns the given assertion. This method improves code readability by surrounding the given assertion withassertThat.Consider for example the following MyButton and MyButtonAssert classes:
As MyButtonAssert implements AssertDelegateTarget, you can usepublic class MyButton extends JButton { private boolean blinking; public boolean isBlinking() { return this.blinking; } public void setBlinking(boolean blink) { this.blinking = blink; } } private static class MyButtonAssert implements AssertDelegateTarget { private MyButton button; MyButtonAssert(MyButton button) { this.button = button; } void isBlinking() { // standard assertion from core Assertions.assertThat assertThat(button.isBlinking()).isTrue(); } void isNotBlinking() { // standard assertion from core Assertions.assertThat assertThat(button.isBlinking()).isFalse(); } }assertThat(buttonAssert).isBlinking();instead ofbuttonAssert.isBlinking();to have easier to read assertions:@Test public void AssertDelegateTarget_example() { MyButton button = new MyButton(); MyButtonAssert buttonAssert = new MyButtonAssert(button); // you can encapsulate MyButtonAssert assertions methods within assertThat assertThat(buttonAssert).isNotBlinking(); // same as : buttonAssert.isNotBlinking(); button.setBlinking(true); assertThat(buttonAssert).isBlinking(); // same as : buttonAssert.isBlinking(); }- Type Parameters:
T- the generic type of the user-defined assert.- Parameters:
assertion- the assertion to return.- Returns:
- the given assertion.
-
assertThat
default <K,V> MapAssert<K,V> assertThat(Map<K,V> actual)
Creates a new instance of.MapAssertReturned type is
MapAssertas it overrides method to annotate them withSafeVarargsavoiding annoying warnings.- Type Parameters:
K- the type of keys in the map.V- the type of values in the map.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractShortAssert<?> assertThat(short actual)
Creates a new instance of.ShortAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractLongAssert<?> assertThat(long actual)
Creates a new instance of.LongAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractLongAssert<?> assertThat(Long actual)
Creates a new instance of.LongAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractLongArrayAssert<?> assertThat(long[] actual)
Creates a new instance of.LongArrayAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <T> ObjectAssert<T> assertThat(T actual)
Creates a new instance of.ObjectAssert- Type Parameters:
T- the type of the actual value.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractStringAssert<?> assertThat(String actual)
Creates a new instance of.CharSequenceAssertfrom aString- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractDateAssert<?> assertThat(Date actual)
Creates a new instance of.DateAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractThrowableAssert<?,? extends Throwable> assertThat(Throwable actual)
Creates a new instance of.ThrowableAssert- Parameters:
actual- the actual value.- Returns:
- the created
ThrowableAssert.
-
assertThat
default AbstractBigDecimalAssert<?> assertThat(BigDecimal actual)
Creates a new instance of.BigDecimalAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractBigIntegerAssert<?> assertThat(BigInteger actual)
Creates a new instance of.BigIntegerAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
default AtomicBooleanAssert assertThat(AtomicBoolean actual)
Create assertion forAtomicBoolean.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AtomicIntegerAssert assertThat(AtomicInteger actual)
Create assertion forAtomicInteger.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AtomicIntegerArrayAssert assertThat(AtomicIntegerArray actual)
Create int[] assertion forAtomicIntegerArray.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <OBJECT> AtomicIntegerFieldUpdaterAssert<OBJECT> assertThat(AtomicIntegerFieldUpdater<OBJECT> actual)
Create assertion forAtomicIntegerFieldUpdater.- Type Parameters:
OBJECT- the type of the object holding the updatable field.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AtomicLongAssert assertThat(AtomicLong actual)
Create assertion forAtomicLong.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AtomicLongArrayAssert assertThat(AtomicLongArray actual)
Create assertion forAtomicLongArray.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <OBJECT> AtomicLongFieldUpdaterAssert<OBJECT> assertThat(AtomicLongFieldUpdater<OBJECT> actual)
Create assertion forAtomicLongFieldUpdater.- Type Parameters:
OBJECT- the type of the object holding the updatable field.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <VALUE> AtomicReferenceAssert<VALUE> assertThat(AtomicReference<VALUE> actual)
Create assertion forAtomicReference.- Type Parameters:
VALUE- the type of the value contained in theAtomicReference.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <ELEMENT> AtomicReferenceArrayAssert<ELEMENT> assertThat(AtomicReferenceArray<ELEMENT> actual)
Create assertion forAtomicReferenceArray.- Type Parameters:
ELEMENT- the type of the value contained in theAtomicReferenceArray.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <FIELD,OBJECT> AtomicReferenceFieldUpdaterAssert<FIELD,OBJECT> assertThat(AtomicReferenceFieldUpdater<OBJECT,FIELD> actual)
Create assertion forAtomicReferenceFieldUpdater.- Type Parameters:
FIELD- the type of the field which gets updated by theAtomicReferenceFieldUpdater.OBJECT- the type of the object holding the updatable field.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <VALUE> AtomicMarkableReferenceAssert<VALUE> assertThat(AtomicMarkableReference<VALUE> actual)
Create assertion forAtomicMarkableReference.- Type Parameters:
VALUE- the type of the value contained in theAtomicMarkableReference.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <VALUE> AtomicStampedReferenceAssert<VALUE> assertThat(AtomicStampedReference<VALUE> actual)
Create assertion forAtomicStampedReference.- Type Parameters:
VALUE- the type of the value contained in theAtomicStampedReference.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractCharSequenceAssert<?,? extends CharSequence> assertThat(CharSequence actual)
Creates a new instance of.CharSequenceAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractCharSequenceAssert<?,? extends CharSequence> assertThat(StringBuilder actual)
Creates a new instance offrom aCharSequenceAssertStringBuilder.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.11.0
-
assertThat
default AbstractCharSequenceAssert<?,? extends CharSequence> assertThat(StringBuffer actual)
Creates a new instance offrom aCharSequenceAssertStringBuffer.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.11.0
-
assertThat
default AbstractShortArrayAssert<?> assertThat(short[] actual)
Creates a new instance of.ShortArrayAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractShortAssert<?> assertThat(Short actual)
Creates a new instance of.ShortAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default ClassAssert assertThat(Class<?> actual)
Creates a new instance ofClassAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractCharacterAssert<?> assertThat(Character actual)
Creates a new instance of.CharacterAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractCharArrayAssert<?> assertThat(char[] actual)
Creates a new instance of.CharArrayAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractCharacterAssert<?> assertThat(char actual)
Creates a new instance of.CharacterAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <T extends Comparable<? super T>> AbstractComparableAssert<?,T> assertThat(T actual)
Creates a new instance ofwith standard comparison semantics.GenericComparableAssert- Type Parameters:
T- the type of actual.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <T> IterableAssert<T> assertThat(Iterable<? extends T> actual)
Creates a new instance of.IterableAssert- Type Parameters:
T- the type of elements.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> FactoryBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> assertThat(Iterable<? extends ELEMENT> actual, AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)
Creates a new instance ofallowing to navigate to anyFactoryBasedNavigableIterableAssertIterableelement in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the
ELEMENT_ASSERTparameter of the givenAssertFactory<ELEMENT, ELEMENT_ASSERT>(AssertJ can't figure it out because of Java type erasure).Example with
Stringelement assertions:Iterable<String> hobbits = newHashSet("frodo", "sam", "pippin"); // build an AssertFactory for StringAssert (much nicer with Java 8 lambdas) AssertFactory<String, StringAssert> stringAssertFactory = new AssertFactory<String, StringAssert>() { @Override public StringAssert createAssert(String string) { return new StringAssert(string); } }; // assertion succeeds with String assertions chained after first() assertThat(hobbits, stringAssertFactory).first() .startsWith("fro") .endsWith("do");- Type Parameters:
ACTUAL- The actual typeELEMENT- The actual elements typeELEMENT_ASSERT- The actual elements AbstractAssert type- Parameters:
actual- the actual value.assertFactory- the factory used to create the elements assert instance.- Returns:
- the created assertion object.
-
assertThat
default <T> IteratorAssert<T> assertThat(Iterator<? extends T> actual)
Creates a new instance of.IteratorAssertBreaking change in version 3.12.0: this method does not return anymore an
IterableAssertbut anIteratorAssert.
In order to access assertions fromIterableAssert, useAbstractIteratorAssert.toIterable().IteratorAssertinstances have limited assertions because it does not consume iterator's elements.Examples:
Iterator<String> bestBasketBallPlayers = getBestBasketBallPlayers(); assertThat(bestBasketBallPlayers).hasNext() // Iterator assertion .toIterable() // switch to Iterable assertions .contains("Jordan", "Magic", "Lebron"); // Iterable assertion- Type Parameters:
T- the type of elements.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> ClassBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> assertThat(ACTUAL actual, Class<ELEMENT_ASSERT> assertClass)
Creates a new instance ofallowing to navigate to anyClassBasedNavigableIterableAssertIterableelement in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the given
assertClass(AssertJ can't find the element assert type by itself because of Java type erasure).Example with
Stringelement assertions:Iterable<String> hobbits = newHashSet("frodo", "sam", "pippin"); // assertion succeeds with String assertions chained after first() assertThat(hobbits, StringAssert.class).first() .startsWith("fro") .endsWith("do");- Type Parameters:
ACTUAL- The actual typeELEMENT- The actual elements typeELEMENT_ASSERT- The actual elements AbstractAssert type- Parameters:
actual- the actual value.assertClass- the class used to create the elements assert instance.- Returns:
- the created assertion object.
-
assertThat
default AbstractBooleanAssert<?> assertThat(Boolean actual)
Creates a new instance of.BooleanAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractBooleanArrayAssert<?> assertThat(boolean[] actual)
Creates a new instance of.BooleanArrayAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractByteAssert<?> assertThat(byte actual)
Creates a new instance of.ByteAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractByteAssert<?> assertThat(Byte actual)
Creates a new instance of.ByteAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractByteArrayAssert<?> assertThat(byte[] actual)
Creates a new instance of.ByteArrayAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractBooleanAssert<?> assertThat(boolean actual)
Creates a new instance of.BooleanAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractFloatAssert<?> assertThat(float actual)
Creates a new instance of.FloatAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractInputStreamAssert<?,? extends InputStream> assertThat(InputStream actual)
Creates a new instance of.InputStreamAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractFileAssert<?> assertThat(File actual)
Creates a new instance of.FileAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <RESULT> FutureAssert<RESULT> assertThat(Future<RESULT> actual)
Create assertion forFuture.- Type Parameters:
RESULT- the type of the value contained in theFuture.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.7.0
-
assertThat
default AbstractPathAssert<?> assertThat(Path actual)
Creates a new instance ofPathAssert- Parameters:
actual- the path to test- Returns:
- the created assertion object
-
assertThat
default AbstractIntArrayAssert<?> assertThat(int[] actual)
Creates a new instance of.IntArrayAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractFloatAssert<?> assertThat(Float actual)
Creates a new instance of.FloatAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractIntegerAssert<?> assertThat(int actual)
Creates a new instance of.IntegerAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractFloatArrayAssert<?> assertThat(float[] actual)
Creates a new instance of.FloatArrayAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractIntegerAssert<?> assertThat(Integer actual)
Creates a new instance of.IntegerAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractDoubleAssert<?> assertThat(double actual)
Creates a new instance of.DoubleAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractDoubleAssert<?> assertThat(Double actual)
Creates a new instance of.DoubleAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <T> ListAssert<T> assertThat(List<? extends T> actual)
Creates a new instance of.ListAssert- Type Parameters:
T- the type of elements.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <ELEMENT,ACTUAL extends List<? extends ELEMENT>,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> ClassBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> assertThat(List<? extends ELEMENT> actual, Class<ELEMENT_ASSERT> assertClass)
Creates a new instance oftallowing to navigate to anyClassBasedNavigableListAssertListelement in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the given
assertClass(AssertJ can't find the element assert type by itself because of Java type erasure).Example with
Stringelement assertions:List<String> hobbits = newArrayList("frodo", "sam", "pippin"); // assertion succeeds with String assertions chained after first() assertThat(hobbits, StringAssert.class).first() .startsWith("fro") .endsWith("do");- Type Parameters:
ACTUAL- The actual typeELEMENT- The actual elements typeELEMENT_ASSERT- The actual elements AbstractAssert type- Parameters:
actual- the actual value.assertClass- the class used to create the elements assert instance.- Returns:
- the created assertion object.
-
assertThat
default <ACTUAL extends List<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> FactoryBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> assertThat(List<? extends ELEMENT> actual, AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)
Creates a new instance ofallowing to navigate to anyFactoryBasedNavigableListAssertListelement in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the
ELEMENT_ASSERTparameter of the givenAssertFactory<ELEMENT, ELEMENT_ASSERT>(AssertJ can't figure it out because of Java type erasure).Example with
Stringelement assertions:List<String> hobbits = newArrayList("frodo", "sam", "pippin"); // build an AssertFactory for StringAssert (much nicer with Java 8 lambdas) AssertFactory<String, StringAssert> stringAssertFactory = new AssertFactory<String, StringAssert>() { @Override public StringAssert createAssert(String string) { return new StringAssert(string); } }; // assertion succeeds with String assertions chained after first() assertThat(hobbits, stringAssertFactory).first() .startsWith("fro") .endsWith("do");- Type Parameters:
ACTUAL- The actual typeELEMENT- The actual elements typeELEMENT_ASSERT- The actual elements AbstractAssert type- Parameters:
actual- the actual value.assertFactory- the factory used to create the elements assert instance.- Returns:
- the created assertion object.
-
assertThat
default <ELEMENT> ListAssert<ELEMENT> assertThat(Stream<? extends ELEMENT> actual)
Creates a new instance offrom the givenListAssertStream.Be aware that the
Streamunder test will be converted to aListwhen an assertions require to inspect its content. Once this is done theStreamcan't reused as it would have been consumed.Calling multiple methods on the returned
ListAssertis safe as it only interacts with theListbuilt from theStream.Examples:
// you can chain multiple assertions on the Stream as it is converted to a List assertThat(Stream.of(1, 2, 3)).contains(1) .doesNotContain(42);The following assertion fails as the Stream under test is converted to a List before being compared to the expected Stream:
// FAIL: the Stream under test is converted to a List and compared to a Stream but a List is not a Stream. assertThat(Stream.of(1, 2, 3)).isEqualTo(Stream.of(1, 2, 3));These assertions succeed as
isEqualToandisSameAschecks references which does not require to convert the Stream to a List.// The following assertions succeed as it only performs reference checking which does not require to convert the Stream to a List Stream<Integer> stream = Stream.of(1, 2, 3); assertThat(stream).isEqualTo(stream) .isSameAs(stream);- Type Parameters:
ELEMENT- the type of elements.- Parameters:
actual- the actualStreamvalue.- Returns:
- the created assertion object.
-
assertThat
default ListAssert<Double> assertThat(DoubleStream actual)
Creates a new instance offrom the givenListAssertDoubleStream.Be aware that the
DoubleStreamunder test will be converted to aListwhen an assertions require to inspect its content. Once this is done theDoubleStreamcan't reused as it would have been consumed.Calling multiple methods on the returned
ListAssertis safe as it only interacts with theListbuilt from theDoubleStream.Examples:
// you can chain multiple assertions on the DoubleStream as it is converted to a List assertThat(DoubleStream.of(1.0, 2.0, 3.0)).contains(1.0) .doesNotContain(42.0);The following assertion fails as the DoubleStream under test is converted to a List before being compared to the expected DoubleStream:
// FAIL: the DoubleStream under test is converted to a List and compared to a DoubleStream but a List is not a DoubleStream. assertThat(DoubleStream.of(1.0, 2.0, 3.0)).isEqualTo(DoubleStream.of(1.0, 2.0, 3.0));These assertions succeed as
isEqualToandisSameAschecks references which does not require to convert the DoubleStream to a List.// The following assertions succeed as it only performs reference checking which does not require to convert the DoubleStream to a List DoubleStream stream = DoubleStream.of(1.0, 2.0, 3.0); assertThat(stream).isEqualTo(stream) .isSameAs(stream);- Parameters:
actual- the actualDoubleStreamvalue.- Returns:
- the created assertion object.
-
assertThat
default ListAssert<Long> assertThat(LongStream actual)
Creates a new instance offrom the givenListAssertLongStream.Be aware that the
LongStreamunder test will be converted to aListwhen an assertions require to inspect its content. Once this is done theLongStreamcan't reused as it would have been consumed.Calling multiple methods on the returned
ListAssertis safe as it only interacts with theListbuilt from theLongStream.Examples:
// you can chain multiple assertions on the LongStream as it is converted to a List assertThat(LongStream.of(1, 2, 3)).contains(1) .doesNotContain(42);The following assertion fails as the LongStream under test is converted to a List before being compared to the expected LongStream:
// FAIL: the LongStream under test is converted to a List and compared to a LongStream but a List is not a LongStream. assertThat(LongStream.of(1, 2, 3)).isEqualTo(LongStream.of(1, 2, 3));These assertions succeed as
isEqualToandisSameAschecks references which does not require to convert the LongStream to a List.// The following assertions succeed as it only performs reference checking which does not require to convert the LongStream to a List LongStream stream = LongStream.of(1, 2, 3); assertThat(stream).isEqualTo(stream) .isSameAs(stream);- Parameters:
actual- the actualLongStreamvalue.- Returns:
- the created assertion object.
-
assertThat
default ListAssert<Integer> assertThat(IntStream actual)
Creates a new instance offrom the givenListAssertIntStream.Be aware that the
IntStreamunder test will be converted to aListwhen an assertions require to inspect its content. Once this is done theIntStreamcan't reused as it would have been consumed.Calling multiple methods on the returned
ListAssertis safe as it only interacts with theListbuilt from theIntStream.Examples:
// you can chain multiple assertions on the IntStream as it is converted to a List assertThat(IntStream.of(1, 2, 3)).contains(1) .doesNotContain(42);The following assertion fails as the IntStream under test is converted to a List before being compared to the expected IntStream:
// FAIL: the IntStream under test is converted to a List and compared to a IntStream but a List is not a IntStream. assertThat(IntStream.of(1, 2, 3)).isEqualTo(IntStream.of(1, 2, 3));These assertions succeed as
isEqualToandisSameAschecks references which does not require to convert the IntStream to a List.// The following assertions succeed as it only performs reference checking which does not require to convert the IntStream to a List IntStream stream = IntStream.of(1, 2, 3); assertThat(stream).isEqualTo(stream) .isSameAs(stream);- Parameters:
actual- the actualIntStreamvalue.- Returns:
- the created assertion object.
-
assertThat
default AbstractDoubleArrayAssert<?> assertThat(double[] actual)
Creates a new instance of.DoubleArrayAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
extractProperty
default Properties<Object> extractProperty(String propertyName)
Only delegate toProperties.extractProperty(String)so that Assertions offers a full feature entry point to all AssertJ features (but you can usePropertiesif you prefer).Typical usage is to chain
extractPropertywithfrommethod, see examples below :// extract simple property values, as no type has been defined the extracted property will be considered as Object // to define the real property type (here String) use extractProperty("name", String.class) instead. assertThat(extractProperty("name").from(fellowshipOfTheRing)) .contains("Boromir", "Gandalf", "Frodo", "Legolas") .doesNotContain("Sauron", "Elrond"); // extracting property works also with user's types (here Race), even though it will be considered as Object // to define the real property type (here String) use extractProperty("name", Race.class) instead. assertThat(extractProperty("race").from(fellowshipOfTheRing)).contains(HOBBIT, ELF).doesNotContain(ORC); // extract nested property on Race assertThat(extractProperty("race.name").from(fellowshipOfTheRing)).contains("Hobbit", "Elf").doesNotContain("Orc");- Parameters:
propertyName- the name of the property to be read from the elements of aIterable. It may be a nested property (e.g. "address.street.number").- Returns:
- the created
Properties. - Throws:
NullPointerException- if the given property name isnull.IllegalArgumentException- if the given property name is empty.
-
extractProperty
default <T> Properties<T> extractProperty(String propertyName, Class<T> propertyType)
Only delegate toProperties.extractProperty(String)so that Assertions offers a full feature entry point to all AssertJ features (but you can usePropertiesif you prefer).Typical usage is to chain
extractPropertywithfrommethod, see examples below :// extract simple property values having a java standard type (here String) assertThat(extractProperty("name", String.class).from(fellowshipOfTheRing)) .contains("Boromir", "Gandalf", "Frodo", "Legolas") .doesNotContain("Sauron", "Elrond"); // extracting property works also with user's types (here Race) assertThat(extractProperty("race", String.class).from(fellowshipOfTheRing)) .contains(HOBBIT, ELF).doesNotContain(ORC); // extract nested property on Race assertThat(extractProperty("race.name", String.class).from(fellowshipOfTheRing)) .contains("Hobbit", "Elf") .doesNotContain("Orc");- Type Parameters:
T- the type of value to extract.- Parameters:
propertyName- the name of the property to be read from the elements of aIterable. It may be a nested property (e.g. "address.street.number").propertyType- the type of property to extract- Returns:
- the created
Properties. - Throws:
NullPointerException- if the given property name isnull.IllegalArgumentException- if the given property name is empty.
-
tuple
default Tuple tuple(Object... values)
Utility method to build nicely aTuplewhen working withAbstractIterableAssert.extracting(String...)orAbstractObjectArrayAssert.extracting(String...)
-
atIndex
default Index atIndex(int index)
Only delegate toIndex.atIndex(int)so that Assertions offers a full feature entry point to all AssertJ features (but you can useIndexif you prefer).Typical usage :
List<Ring> elvesRings = newArrayList(vilya, nenya, narya); assertThat(elvesRings).contains(vilya, atIndex(0)).contains(nenya, atIndex(1)).contains(narya, atIndex(2));- Parameters:
index- the value of the index.- Returns:
- the created
Index. - Throws:
IllegalArgumentException- if the given value is negative.
-
within
default Offset<Double> within(Double value)
Alias foroffset(Double)to use with isCloseTo assertions.Typical usage :
assertThat(8.1).isCloseTo(8.0, within(0.1));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.
-
within
default Offset<BigDecimal> within(BigDecimal value)
Assertions entry point for BigDecimalOffsetto use with isCloseTo assertions.Typical usage :
assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), within(BigDecimal.ONE));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.
-
within
default Offset<Float> within(Float value)
Alias foroffset(Float)to use with isCloseTo assertions.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, within(0.2f));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.
-
withPrecision
default Offset<Double> withPrecision(Double value)
Assertions entry point for doubleOffset.Typical usage :
assertThat(8.1).isEqualTo(8.0, offset(0.1));- Parameters:
value- the allowed offset- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
withPrecision
default Offset<Float> withPrecision(Float value)
Assertions entry point for floatOffset.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, offset(0.2f));- Parameters:
value- the allowed offset- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
within
default Offset<BigInteger> within(BigInteger value)
Assertions entry point for BigIntegerOffsetto use with isCloseTo assertions.Typical usage :
assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), within(new BigInteger("2")));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
within
default Offset<Byte> within(Byte value)
Assertions entry point for ByteOffsetto use with isCloseTo assertions.Typical usage :
assertThat((byte) 10).isCloseTo((byte) 11, within((byte) 1));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
within
default Offset<Integer> within(Integer value)
Assertions entry point for IntegerOffsetto use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, within(1));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
within
default Offset<Short> within(Short value)
Assertions entry point for ShortOffsetto use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, within(1));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
within
default Offset<Long> within(Long value)
Assertions entry point for LongOffsetto use with isCloseTo assertions.Typical usage :
assertThat(5l).isCloseTo(7l, within(2l));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
within
default TemporalUnitOffset within(long value, TemporalUnit unit)
Assertions entry point forTemporalUnitOffsetwith with less than or equal condition to use with isCloseTo temporal assertions.Typical usage :
LocalTime _07_10 = LocalTime.of(7, 10); LocalTime _07_12 = LocalTime.of(7, 12); assertThat(_07_10).isCloseTo(_07_12, within(5, ChronoUnit.MINUTES));- Parameters:
value- the allowed offsetunit- theTemporalUnitof the offset- Returns:
- the created
Offset. - Since:
- 3.9.0
-
withinPercentage
default Percentage withinPercentage(Double value)
Assertions entry point for DoublePercentageto use with isCloseTo assertions for percentages.Typical usage :
assertThat(11.0).isCloseTo(10.0, withinPercentage(10.0));- Parameters:
value- the required precision percentage- Returns:
- the created
Percentage. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
withinPercentage
default Percentage withinPercentage(Integer value)
Assertions entry point for IntegerPercentageto use with isCloseTo assertions for percentages.Typical usage :
assertThat(11).isCloseTo(10, withinPercentage(10));- Parameters:
value- the required precision percentage- Returns:
- the created
Percentage. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
withinPercentage
default Percentage withinPercentage(Long value)
Assertions entry point for LongPercentageto use with isCloseTo assertions for percentages.Typical usage :
assertThat(11L).isCloseTo(10L, withinPercentage(10L));- Parameters:
value- the required precision percentage- Returns:
- the created
Percentage. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default Offset<Double> byLessThan(Double value)
Alias foroffset(Double)to use with isCloseTo assertions.Typical usage :
assertThat(8.1).isCloseTo(8.0, byLessThan(0.1));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default Offset<Float> byLessThan(Float value)
Alias foroffset(Float)to use with isCloseTo assertions.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, byLessThan(0.2f));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default Offset<BigDecimal> byLessThan(BigDecimal value)
Assertions entry point for BigDecimalOffsetto use with isCloseTo assertions.Typical usage :
assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), byLessThan(BigDecimal.ONE));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default Offset<BigInteger> byLessThan(BigInteger value)
Assertions entry point for BigIntegerOffsetto use with isCloseTo assertions.Typical usage :
assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), byLessThan(new BigInteger("2")));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default Offset<Byte> byLessThan(Byte value)
Assertions entry point for ByteOffsetto use with isCloseTo assertions.Typical usage :
assertThat((byte) 10).isCloseTo((byte) 11, byLessThan((byte) 1));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default Offset<Integer> byLessThan(Integer value)
Assertions entry point for IntegerOffsetto use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, byLessThan(1));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default Offset<Short> byLessThan(Short value)
Assertions entry point for ShortOffsetto use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, byLessThan(1));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default Offset<Long> byLessThan(Long value)
Assertions entry point for LongOffsetto use with isCloseTo assertions.Typical usage :
assertThat(5l).isCloseTo(7l, byLessThan(2l));- Parameters:
value- the value of the offset.- Returns:
- the created
Offset. - Throws:
NullPointerException- if the given value isnull.IllegalArgumentException- if the given value is negative.- Since:
- 3.9.0
-
byLessThan
default TemporalUnitOffset byLessThan(long value, TemporalUnit unit)
Assertions entry point forTemporalUnitOffsetwith strict less than condition to use withisCloseTotemporal assertions.Typical usage :
LocalTime _07_10 = LocalTime.of(7, 10); LocalTime _07_12 = LocalTime.of(7, 12); assertThat(_07_10).isCloseTo(_07_12, byLessThan(5, ChronoUnit.MINUTES));- Parameters:
value- the value of the offset.unit- theTemporalUnitof the offset.- Returns:
- the created
Offset. - Since:
- 3.9.0
-
from
default <F,T> Function<F,T> from(Function<F,T> extractor)
A syntax sugar to write fluent assertion usingAbstractObjectAssert.returns(Object, Function).Example:
Jedi yoda = new Jedi("Yoda", "Green"); assertThat(yoda).returns("Yoda", from(Jedi::getName)) .returns(2.4, from(Jedi::getHeight)) .returns(150, from(Jedi::getWeight));- Type Parameters:
F- Type of test subjectT- Type of the property under the assertion- Parameters:
extractor- A function to extract test subject's property- Returns:
- same instance of
extractor - Since:
- 3.9.0
-
anyOf
default <T> Condition<T> anyOf(Iterable<? extends Condition<? super T>> conditions)
Creates a newAnyOf- Type Parameters:
T- the type of object the given condition accept.- Parameters:
conditions- the conditions to evaluate.- Returns:
- the created
AnyOf. - Throws:
NullPointerException- if the given iterable isnull.NullPointerException- if any of the elements in the given iterable isnull.
-
anyOf
default <T> Condition<T> anyOf(Condition<? super T>... conditions)
Only delegate toAnyOf.anyOf(Condition...)so that Assertions offers a full feature entry point to all AssertJ features (but you can useAnyOfif you prefer).Typical usage (
jediandsithareCondition) :assertThat("Vader").is(anyOf(jedi, sith));- Type Parameters:
T- the type of object the given condition accept.- Parameters:
conditions- the conditions to evaluate.- Returns:
- the created
AnyOf.
-
doesNotHave
default <T> DoesNotHave<T> doesNotHave(Condition<? super T> condition)
Creates a new.DoesNotHave- Type Parameters:
T- the type of object the given condition accept.- Parameters:
condition- the condition to inverse.- Returns:
- The DoesNotHave condition created.
-
contentOf
default String contentOf(File file, String charsetName)
Loads the text content of a file, so that it can be passed toassertThat(String).Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
assertThat(File).- Parameters:
file- the file.charsetName- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
IllegalArgumentException- if the given character set is not supported on this platform.UncheckedIOException- if an I/O exception occurs.
-
contentOf
default String contentOf(File file)
Loads the text content of a file with the default character set, so that it can be passed toassertThat(String).Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
assertThat(File).- Parameters:
file- the file.- Returns:
- the content of the file.
- Throws:
UncheckedIOException- if an I/O exception occurs.
-
contentOf
default String contentOf(File file, Charset charset)
Loads the text content of a file, so that it can be passed toassertThat(String).Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
assertThat(File).- Parameters:
file- the file.charset- the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException- if the given charset isnull.UncheckedIOException- if an I/O exception occurs.
-
linesOf
default List<String> linesOf(File file)
Loads the text content of a file into a list of strings with the default charset, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file- the file.- Returns:
- the content of the file.
- Throws:
NullPointerException- if the given charset isnull.UncheckedIOException- if an I/O exception occurs.
-
linesOf
default List<String> linesOf(File file, String charsetName)
Loads the text content of a file into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file- the file.charsetName- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException- if the given charset isnull.UncheckedIOException- if an I/O exception occurs.
-
linesOf
default List<String> linesOf(File file, Charset charset)
Loads the text content of a file into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file- the file.charset- the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException- if the given charset isnull.UncheckedIOException- if an I/O exception occurs.
-
setRemoveAssertJRelatedElementsFromStackTrace
default void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace)
Sets whether we remove elements related to AssertJ from assertion error stack trace.- Parameters:
removeAssertJRelatedElementsFromStackTrace- flag.
-
failBecauseExceptionWasNotThrown
default <T> T failBecauseExceptionWasNotThrown(Class<? extends Throwable> throwableClass)
Throws anAssertionErrorwith a message explaining that aThrowableof given class was expected to be thrown but had not been.Assertions.shouldHaveThrown(Class)can be used as a replacement.- Type Parameters:
T- dummy return value type- Parameters:
throwableClass- the Throwable class that was expected to be thrown.- Returns:
- nothing, it's just to be used in doSomething(optional.orElse(() -> failBecauseExceptionWasNotThrown(IOException.class)));.
- Throws:
AssertionError- with a message explaining that aThrowableof given class was expected to be thrown but had not been.
-
shouldHaveThrown
default <T> T shouldHaveThrown(Class<? extends Throwable> throwableClass)
Throws anAssertionErrorwith a message explaining that aThrowableof given class was expected to be thrown but had not been.- Type Parameters:
T- dummy return value type- Parameters:
throwableClass- the Throwable class that was expected to be thrown.- Returns:
- nothing, it's just to be used in doSomething(optional.orElse(() -> shouldHaveThrown(IOException.class)));.
- Throws:
AssertionError- with a message explaining that aThrowableof given class was expected to be thrown but had not been.- Since:
- 3.9.0
-
setMaxLengthForSingleLineDescription
default void setMaxLengthForSingleLineDescription(int maxLengthForSingleLineDescription)
In error messages, sets the threshold when iterable/array formatting will on one line (if their String description is less than this parameter) or it will be formatted with one element per line.The following array will be formatted on one line as its length < 80:
whereas this array is formatted on multiple lines (one element per line)String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"]String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards! (Discworld)"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards! (Discworld)"]- Parameters:
maxLengthForSingleLineDescription- the maximum length for an iterable/array to be displayed on one line- Since:
- 3.9.0
-
setMaxElementsForPrinting
default void setMaxElementsForPrinting(int maxElementsForPrinting)
In error messages, sets the threshold for how many elements from one iterable/array/map will be included in the in the description. E.q. When this method is called with a value of3.The following array will be formatted entirely as it's length is <= 3:
whereas this array is formatted only with it's first 3 elements, followed byString[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"]...:String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards!"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", ...]- Parameters:
maxElementsForPrinting- the maximum elements that would be printed from one iterable/array/map- Since:
- 3.9.0
-
setAllowExtractingPrivateFields
default void setAllowExtractingPrivateFields(boolean allowExtractingPrivateFields)
Globally sets whetherandIterableAssert#extracting(String)should be allowed to extract private fields, if not and they try it fails with exception.ObjectArrayAssert#extracting(String)- Parameters:
allowExtractingPrivateFields- allow private fields extraction. Defaulttrue.
-
setAllowComparingPrivateFields
default void setAllowComparingPrivateFields(boolean allowComparingPrivateFields)
Globally sets whether the use of private fields is allowed for comparison. The following (incomplete) list of methods will be impacted by this change :-
AbstractIterableAssert.usingElementComparatorOnFields(java.lang.String...) AbstractObjectAssert.isEqualToComparingFieldByField(Object)
falseand these methods try to compare private fields, it will fail with an exception.- Parameters:
allowComparingPrivateFields- allow private fields comparison. Defaulttrue.- Since:
- 3.9.0
-
-
setExtractBareNamePropertyMethods
default void setExtractBareNamePropertyMethods(boolean barenamePropertyMethods)
Globally sets whether the extractor considers bare-named property methods likeString name(). Defaults to enabled.- Parameters:
barenamePropertyMethods- whether bare-named property methods are found
-
setLenientDateParsing
default void setLenientDateParsing(boolean value)
Instead of using default strict date/time parsing, it is possible to use lenient parsing mode for default date formats parser to interpret inputs that do not precisely match supported date formats (lenient parsing).With strict parsing, inputs must match exactly date/time format.
Example:
To revert to default strict date parsing, callfinal Date date = Dates.parse("2001-02-03"); final Date dateTime = parseDatetime("2001-02-03T04:05:06"); final Date dateTimeWithMs = parseDatetimeWithMs("2001-02-03T04:05:06.700"); Assertions.setLenientDateParsing(true); // assertions will pass assertThat(date).isEqualTo("2001-01-34"); assertThat(date).isEqualTo("2001-02-02T24:00:00"); assertThat(date).isEqualTo("2001-02-04T-24:00:00.000"); assertThat(dateTime).isEqualTo("2001-02-03T04:05:05.1000"); assertThat(dateTime).isEqualTo("2001-02-03T04:04:66"); assertThat(dateTimeWithMs).isEqualTo("2001-02-03T04:05:07.-300"); // assertions will fail assertThat(date).hasSameTimeAs("2001-02-04"); // different date assertThat(dateTime).hasSameTimeAs("2001-02-03 04:05:06"); // leniency does not help heresetLenientDateParsing(false).- Parameters:
value- whether lenient parsing mode should be enabled or not- Since:
- 3.9.0
-
registerCustomDateFormat
default void registerCustomDateFormat(DateFormat userCustomDateFormat)
Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String).User date formats are used before default ones in the order they have been registered (first registered, first used).
AssertJ is gonna use any date formats registered with one of these methods :
AbstractDateAssert.withDateFormat(String)AbstractDateAssert.withDateFormat(java.text.DateFormat)registerCustomDateFormat(java.text.DateFormat)registerCustomDateFormat(String)
Beware that AssertJ will use the newly registered format for all remaining Date assertions in the test suite
To revert to default formats only, call
useDefaultDateFormatsOnly()orAbstractDateAssert.withDefaultDateFormatsOnly().Code examples:
Date date = ... // set to 2003 April the 26th assertThat(date).isEqualTo("2003-04-26"); try { // date with a custom format : failure since the default formats don't match. assertThat(date).isEqualTo("2003/04/26"); } catch (AssertionError e) { assertThat(e).hasMessage("Failed to parse 2003/04/26 with any of these date formats: " + "[yyyy-MM-dd'T'HH:mm:ss.SSS, yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]"); } // registering a custom date format to make the assertion pass registerCustomDateFormat(new SimpleDateFormat("yyyy/MM/dd")); // registerCustomDateFormat("yyyy/MM/dd") would work to. assertThat(date).isEqualTo("2003/04/26"); // the default formats are still available and should work assertThat(date).isEqualTo("2003-04-26");- Parameters:
userCustomDateFormat- the new Date format used for String based Date assertions.
-
registerCustomDateFormat
default void registerCustomDateFormat(String userCustomDateFormatPattern)
Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String).User date formats are used before default ones in the order they have been registered (first registered, first used).
AssertJ is gonna use any date formats registered with one of these methods :
AbstractDateAssert.withDateFormat(String)AbstractDateAssert.withDateFormat(java.text.DateFormat)registerCustomDateFormat(java.text.DateFormat)registerCustomDateFormat(String)
Beware that AssertJ will use the newly registered format for all remaining Date assertions in the test suite.
To revert to default formats only, call
useDefaultDateFormatsOnly()orAbstractDateAssert.withDefaultDateFormatsOnly().Code examples:
Date date = ... // set to 2003 April the 26th assertThat(date).isEqualTo("2003-04-26"); try { // date with a custom format : failure since the default formats don't match. assertThat(date).isEqualTo("2003/04/26"); } catch (AssertionError e) { assertThat(e).hasMessage("Failed to parse 2003/04/26 with any of these date formats: " + "[yyyy-MM-dd'T'HH:mm:ss.SSS, yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]"); } // registering a custom date format to make the assertion pass registerCustomDateFormat("yyyy/MM/dd"); assertThat(date).isEqualTo("2003/04/26"); // the default formats are still available and should work assertThat(date).isEqualTo("2003-04-26");- Parameters:
userCustomDateFormatPattern- the new Date format pattern used for String based Date assertions.
-
useDefaultDateFormatsOnly
default void useDefaultDateFormatsOnly()
Remove all registered custom date formats => use only the defaults date formats to parse string as date.Beware that the default formats are expressed in the current local timezone.
Defaults date format are:
yyyy-MM-dd'T'HH:mm:ss.SSSyyyy-MM-dd HH:mm:ss.SSS(forTimestampString representation support)yyyy-MM-dd'T'HH:mm:ssyyyy-MM-dd
Example of valid string date representations:
2003-04-26T03:01:02.9992003-04-26 03:01:02.9992003-04-26T13:01:022003-04-26
-
assertThat
default AbstractZonedDateTimeAssert<?> assertThat(ZonedDateTime actual)
Creates a new instance of.ZonedDateTimeAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <RESULT> CompletableFutureAssert<RESULT> assertThat(CompletableFuture<RESULT> future)
Create assertion forCompletableFuture.- Type Parameters:
RESULT- the type of the value contained in theCompletableFuture.- Parameters:
future- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <RESULT> CompletableFutureAssert<RESULT> assertThat(CompletionStage<RESULT> completionStage)
Create assertion forCompletionStageby converting it to aCompletableFutureand returning aCompletableFutureAssert.If the given
CompletionStageis null, theCompletableFuturein the returnedCompletableFutureAssertwill also be null.- Type Parameters:
RESULT- the type of the value contained in theCompletionStage.- Parameters:
completionStage- the actualCompletionStage.- Returns:
- the created assertion object.
-
assertThat
default <VALUE> OptionalAssert<VALUE> assertThat(Optional<VALUE> optional)
Create assertion forOptional.- Type Parameters:
VALUE- the type of the value contained in theOptional.- Parameters:
optional- the actual value.- Returns:
- the created assertion object.
-
assertThat
default OptionalDoubleAssert assertThat(OptionalDouble optional)
Create assertion forOptionalDouble.- Parameters:
optional- the actual value.- Returns:
- the created assertion object.
-
assertThat
default OptionalIntAssert assertThat(OptionalInt optional)
Create assertion forOptionalInt.- Parameters:
optional- the actual value.- Returns:
- the created assertion object.
-
assertThat
default OptionalLongAssert assertThat(OptionalLong optional)
Create assertion forOptionalLong.- Parameters:
optional- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractLocalDateTimeAssert<?> assertThat(LocalDateTime localDateTime)
Creates a new instance of.LocalDateTimeAssert- Parameters:
localDateTime- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractLocalDateAssert<?> assertThat(LocalDate localDate)
Creates a new instance of.LocalDateAssert- Parameters:
localDate- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractLocalTimeAssert<?> assertThat(LocalTime localTime)
Creates a new instance of.LocalTimeAssert- Parameters:
localTime- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractInstantAssert<?> assertThat(Instant actual)
Creates a new instance of.InstantAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.7.0
-
assertThat
default AbstractOffsetTimeAssert<?> assertThat(OffsetTime offsetTime)
Creates a new instance of.OffsetTimeAssert- Parameters:
offsetTime- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractOffsetDateTimeAssert<?> assertThat(OffsetDateTime offsetDateTime)
Creates a new instance of.OffsetTimeAssert- Parameters:
offsetDateTime- the actual value.- Returns:
- the created assertion object.
-
assertThatThrownBy
default AbstractThrowableAssert<?,? extends Throwable> assertThatThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Allows to capture and then assert on aThrowable(easier done with lambdas).Example :
If the provided@Test public void testException() { assertThatThrownBy(() -> { throw new Exception("boom!") }).isInstanceOf(Exception.class) .hasMessageContaining("boom"); }ThrowableAssert.ThrowingCallabledoes not raise an exception, an error is immediately thrown, in that case the test description provided withas(String, Object...)is not honored.
To use a test description, usecatchThrowable(ThrowableAssert.ThrowingCallable)as shown below:
Alternatively you can also use// assertion will fail but "display me" won't appear in the error assertThatThrownBy(() -> {}).as("display me") .isInstanceOf(Exception.class); // assertion will fail AND "display me" will appear in the error Throwable thrown = catchThrowable(() -> {}); assertThat(thrown).as("display me") .isInstanceOf(Exception.class);assertThatCode(ThrowingCallable)for the test description provided withas(String, Object...)to always be honored.- Parameters:
shouldRaiseThrowable- TheThrowableAssert.ThrowingCallableor lambda with the code that should raise the throwable.- Returns:
- the created
ThrowableAssert.
-
assertThatThrownBy
default AbstractThrowableAssert<?,? extends Throwable> assertThatThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, String description, Object... args)
Allows to capture and then assert on aThrowablelikeassertThatThrownBy(ThrowingCallable)but this method let you set the assertion description the same way you do withas(String, Object...).Example:
If the provided@Test public void testException() { // if this assertion failed (but it doesn't), the error message would start with [Test explosive code] assertThatThrownBy(() -> { throw new IOException("boom!") }, "Test explosive code") .isInstanceOf(IOException.class) .hasMessageContaining("boom"); }ThrowingCallabledoes not raise an exception, an error is immediately thrown.The test description provided is honored but not the one with
as(String, Object...), example:// assertion will fail but "display me" won't appear in the error message assertThatThrownBy(() -> {}).as("display me") .isInstanceOf(Exception.class); // assertion will fail AND "display me" will appear in the error message assertThatThrownBy(() -> {}, "display me") .isInstanceOf(Exception.class);- Parameters:
shouldRaiseThrowable- TheThrowableAssert.ThrowingCallableor lambda with the code that should raise the throwable.description- the new description to set.args- optional parameter if description is a format String.- Returns:
- the created
ThrowableAssert. - Since:
- 3.9.0
-
assertThatCode
default AbstractThrowableAssert<?,? extends Throwable> assertThatCode(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable)
Allows to capture and then assert on aThrowablemore easily when used with Java 8 lambdas.Example :
If the providedThrowingCallable callable = () -> { throw new Exception("boom!"); }; // assertion succeeds assertThatCode(callable).isInstanceOf(Exception.class) .hasMessageContaining("boom"); // assertion fails assertThatCode(callable).doesNotThrowAnyException();ThrowableAssert.ThrowingCallabledoes not validate against next assertions, an error is immediately raised, in that case the test description provided withas(String, Object...)is not honored.
To use a test description, usecatchThrowable(ThrowableAssert.ThrowingCallable)as shown below.ThrowingCallable doNothing = () -> { // do nothing }; // assertion fails and "display me" appears in the assertion error assertThatCode(doNothing).as("display me") .isInstanceOf(Exception.class); // assertion will fail AND "display me" will appear in the error Throwable thrown = catchThrowable(doNothing); assertThatCode(thrown).as("display me") .isInstanceOf(Exception.class);This method was not named
assertThatbecause the java compiler reported it ambiguous when used directly with a lambda :(- Parameters:
shouldRaiseOrNotThrowable- TheThrowableAssert.ThrowingCallableor lambda with the code that should raise the throwable.- Returns:
- The captured exception or
nullif none was raised by the callable. - Since:
- 3.7.0
-
assertThatObject
default <T> ObjectAssert<T> assertThatObject(T actual)
Creates a new instance offor any object.ObjectAssertThis overload is useful, when an overloaded method of assertThat(...) takes precedence over the generic
assertThat(Object).Example:
Cast necessary becauseassertThat(List)"forgets" actual type:
No cast needed, but also no additional list assertions:assertThat(new LinkedList<>(asList("abc"))).matches(list -> ((Deque<String>) list).getFirst().equals("abc"));assertThatObject(new LinkedList<>(asList("abc"))).matches(list -> list.getFirst().equals("abc"));- Type Parameters:
T- the type of the actual value.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.12.0
-
catchThrowable
default Throwable catchThrowable(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Allows to catch anThrowablemore easily when used with Java 8 lambdas.This caught
Throwablecan then be asserted.Example:
@Test public void testException() { // when Throwable thrown = catchThrowable(() -> { throw new Exception("boom!"); }); // then assertThat(thrown).isInstanceOf(Exception.class) .hasMessageContaining("boom"); }- Parameters:
shouldRaiseThrowable- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
nullif none was raised by the callable. - See Also:
catchThrowableOfType(ThrowableAssert.ThrowingCallable, Class)
-
catchThrowableOfType
default <THROWABLE extends Throwable> THROWABLE catchThrowableOfType(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, Class<THROWABLE> type)
Allows catching aThrowableof a specific type.A call is made to
catchThrowable(ThrowingCallable), if no exception is throwncatchThrowableOfTypereturns null, otherwise it checks that the caughtThrowablehas the specified type then casts it to it before returning it, making it convenient to perform subtype-specific assertions on the result.Example:
class CustomParseException extends Exception { int line; int column; public CustomParseException(String msg, int l, int c) { super(msg); line = l; column = c; } } CustomParseException e = catchThrowableOfType(() -> { throw new CustomParseException("boom!", 1, 5); }, CustomParseException.class); // assertions pass assertThat(e).hasMessageContaining("boom"); assertThat(e.line).isEqualTo(1); assertThat(e.column).isEqualTo(5); // fails as CustomParseException is not a RuntimeException catchThrowableOfType(() -> { throw new CustomParseException("boom!", 1, 5); }, RuntimeException.class);- Type Parameters:
THROWABLE- theThrowabletype.- Parameters:
shouldRaiseThrowable- The lambda with the code that should raise the exception.type- The type of exception that the code is expected to raise.- Returns:
- The captured exception or
nullif none was raised by the callable. - Since:
- 3.9.0
- See Also:
catchThrowable(ThrowableAssert.ThrowingCallable)
-
assertThatExceptionOfType
default <T extends Throwable> ThrowableTypeAssert<T> assertThatExceptionOfType(Class<? extends T> exceptionType)
Entry point to check that an exception of type T is thrown by a giventhrowingCallablewhich allows to chain assertions on the thrown exception.Example:
This method is more or less the same ofassertThatExceptionOfType(IOException.class) .isThrownBy(() -> { throw new IOException("boom!"); }) .withMessage("boom!");assertThatThrownBy(ThrowableAssert.ThrowingCallable)but in a more natural way.- Type Parameters:
T- the exception type.- Parameters:
exceptionType- the exception type class.- Returns:
- the created
ThrowableTypeAssert.
-
assertThatNullPointerException
default ThrowableTypeAssert<NullPointerException> assertThatNullPointerException()
Alias forassertThatExceptionOfType(Class)forNullPointerException.- Returns:
- the created
ThrowableTypeAssert. - Since:
- 3.9.0
-
assertThatIllegalArgumentException
default ThrowableTypeAssert<IllegalArgumentException> assertThatIllegalArgumentException()
Alias forassertThatExceptionOfType(Class)forIllegalArgumentException.- Returns:
- the created
ThrowableTypeAssert. - Since:
- 3.9.0
-
assertThatIOException
default ThrowableTypeAssert<IOException> assertThatIOException()
Alias forassertThatExceptionOfType(Class)forIOException.- Returns:
- the created
ThrowableTypeAssert. - Since:
- 3.9.0
-
assertThatIllegalStateException
default ThrowableTypeAssert<IllegalStateException> assertThatIllegalStateException()
Alias forassertThatExceptionOfType(Class)forIllegalStateException.- Returns:
- the created
ThrowableTypeAssert. - Since:
- 3.9.0
-
assertThat
default <T> PredicateAssert<T> assertThat(Predicate<T> actual)
Create assertion forPredicate.- Type Parameters:
T- the type of the value contained in thePredicate.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default IntPredicateAssert assertThat(IntPredicate actual)
Create assertion forIntPredicate.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default LongPredicateAssert assertThat(LongPredicate actual)
Create assertion forLongPredicate.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default DoublePredicateAssert assertThat(DoublePredicate actual)
Create assertion forDoublePredicate.- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractUrlAssert<?> assertThat(URL actual)
Creates a new instance of.UrlAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default AbstractUriAssert<?> assertThat(URI actual)
Creates a new instance of.UriAssert- Parameters:
actual- the actual value.- Returns:
- the created assertion object.
-
assertThat
default <T> T assertThat(AssertProvider<T> component)
Delegates the creation of theAssertto theAssertProvider.assertThat()of the given component.Read the comments on
AssertProviderfor an example of its usage.- Type Parameters:
T- the AssertProvider wrapped type.- Parameters:
component- the component that creates its own assert- Returns:
- the associated
Assertof the given component
-
filter
default <E> Filters<E> filter(E[] array)
Only delegate toFilters.filter(Object[])so that Assertions offers a full feature entry point to all AssertJ features (but you can useFiltersif you prefer).Note that the given array is not modified, the filters are performed on an
Iterablecopy of the array.Typical usage with
Condition:assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);and with filter language based on java bean property :
assertThat(filter(players).with("pointsPerGame").greaterThan(20).and("assistsPerGame").greaterThan(7).get()) .containsOnly(james, rose);- Type Parameters:
E- the array elements type.- Parameters:
array- the array to filter.- Returns:
- the created
.Filters
-
filter
default <E> Filters<E> filter(Iterable<E> iterableToFilter)
Only delegate toFilters.filter(Object[])so that Assertions offers a full feature entry point to all AssertJ features (but you can useFiltersif you prefer).Note that the given
Iterableis not modified, the filters are performed on a copy.Typical usage with
Condition:assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);and with filter language based on java bean property :
assertThat(filter(players).with("pointsPerGame").greaterThan(20) .and("assistsPerGame").greaterThan(7).get()) .containsOnly(james, rose);
-
in
default InFilter in(Object... values)
Create aFilterOperatorto use infilteredOn(String, FilterOperation)to express a filter keeping all Iterable elements whose property/field value matches one of the given values.As often, an example helps:
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", in(800, 26)) .containsOnly(yoda, obiwan, luke);- Parameters:
values- values to match (one match is sufficient)- Returns:
- the created "in" filter
- Since:
- 3.9.0
-
notIn
default NotInFilter notIn(Object... valuesNotToMatch)
Create aFilterOperatorto use infilteredOn(String, FilterOperation)to express a filter keeping all Iterable elements whose property/field value matches does not match any of the given values.As often, an example helps:
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", notIn(800, 50)) .containsOnly(luke);- Parameters:
valuesNotToMatch- values not to match (none of the values must match)- Returns:
- the created "not in" filter
- Since:
- 3.9.0
-
not
default NotFilter not(Object valueNotToMatch)
Create aFilterOperatorto use infilteredOn(String, FilterOperation)to express a filter keeping all Iterable elements whose property/field value matches does not match the given value.As often, an example helps:
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", not(800)) .containsOnly(luke, noname);- Parameters:
valueNotToMatch- the value not to match- Returns:
- the created "not" filter
- Since:
- 3.9.0
-
contentOf
default String contentOf(URL url, Charset charset)
Loads the text content of a URL, so that it can be passed toassertThat(String).Note that this will load the entire contents in memory.
- Parameters:
url- the URL.charset- the character set to use.- Returns:
- the content of the URL.
- Throws:
NullPointerException- if the given charset isnull.UncheckedIOException- if an I/O exception occurs.- Since:
- 3.9.0
-
contentOf
default String contentOf(URL url, String charsetName)
Loads the text content of a URL, so that it can be passed toassertThat(String).Note that this will load the entire contents in memory.
- Parameters:
url- the URL.charsetName- the name of the character set to use.- Returns:
- the content of the URL.
- Throws:
IllegalArgumentException- if the given character set is not supported on this platform.UncheckedIOException- if an I/O exception occurs.- Since:
- 3.9.0
-
contentOf
default String contentOf(URL url)
Loads the text content of a URL with the default character set, so that it can be passed toassertThat(String).Note that this will load the entire file in memory; for larger files.
- Parameters:
url- the URL.- Returns:
- the content of the file.
- Throws:
UncheckedIOException- if an I/O exception occurs.- Since:
- 3.9.0
-
linesOf
default List<String> linesOf(URL url)
Loads the text content of a URL into a list of strings with the default charset, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url- the URL.- Returns:
- the content of the file.
- Throws:
NullPointerException- if the given charset isnull.UncheckedIOException- if an I/O exception occurs.- Since:
- 3.9.0
-
linesOf
default List<String> linesOf(URL url, Charset charset)
Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url- the URL.charset- the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException- if the given charset isnull.UncheckedIOException- if an I/O exception occurs.- Since:
- 3.9.0
-
linesOf
default List<String> linesOf(URL url, String charsetName)
Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url- the URL.charsetName- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException- if the given charset isnull.UncheckedIOException- if an I/O exception occurs.- Since:
- 3.9.0
-
useRepresentation
default void useRepresentation(Representation customRepresentation)
Register aRepresentationthat will be used in all following assertions.Representationare used to format types in assertions error messages.An alternative way of using a different representation is to register one as a service, this approach is described in
Representation, it requires more work than this method but has the advantage of not having to do anything in your tests and it would be applied to all the tests globallyExample :
private class Example {} private class CustomRepresentation extends StandardRepresentation { // override needed to hook specific formatting @Override public String toStringOf(Object o) { if (o instanceof Example) return "Example"; // fallback to default formatting. return super.toStringOf(o); } // change String representation @Override protected String toStringOf(String s) { return "$" + s + "$"; } } Assertions.useRepresentation(new CustomRepresentation()); // this assertion fails ... assertThat(new Example()).isNull(); // ... with error : // "expected:<[null]> but was:<[Example]>" // this one fails ... assertThat("foo").startsWith("bar"); // ... with error : // Expecting: // <$foo$> // to start with: // <$bar$>- Parameters:
customRepresentation- theRepresentationto use- Since:
- 3.9.0
-
registerFormatterForType
default <T> void registerFormatterForType(Class<T> type, Function<T,String> formatter)
Assertions error messages uses aRepresentationto format the different types involved, using this method you can control the formatting of a given type by providing a specific formatter.Registering a formatter makes it available for all AssertJ
Representation:Example :
// without specific formatter assertThat(STANDARD_REPRESENTATION.toStringOf(123L)).isEqualTo("123L"); // register a formatter for Long Assertions.registerFormatterForType(Long.class, value -> "$" + value + "$"); // now Long will be formatted between in $$ in error message. assertThat(STANDARD_REPRESENTATION.toStringOf(longNumber)).isEqualTo("$123$"); // fails with error : expected:<$456$> but was:<$123$> assertThat(123L).isEqualTo(456L);- Type Parameters:
T- the type of format.- Parameters:
type- the class of the type to formatformatter- the formatterFunction- Since:
- 3.9.0
-
useDefaultRepresentation
default void useDefaultRepresentation()
Fallback to useStandardRepresentationto revert the effect of callinguseRepresentation(Representation).- Since:
- 3.9.0
-
-