Class BDDAssertions
- All Implemented Interfaces:
InstanceOfAssertFactories
The difference with the Assertions
class is that entry point methods are named then
instead of
assertThat
.
For example:
@Test
public void bdd_assertions_example() {
//given
List<BasketBallPlayer> bulls = new ArrayList<>();
//when
bulls.add(rose);
bulls.add(noah);
then(bulls).contains(rose, noah).doesNotContain(james);
}
Use and
to avoid clash with other libraries (like BDDMockito) exposing 'then(object)
'.
You might have to ignore a warning like: The static method BDDAssertions.then() should be accessed in a static way.- Author:
- Gonzalo Müller, Alex Ruiz, Yvonne Wang, David DIDIER, Ted Young, Joel Costigliola, Matthieu Baechler, Mikhail Mazursky, Nicolas François, Julien Meddah, William Delanoue, Mariusz Smykula
-
Field Summary
Modifier and TypeFieldDescriptionstatic final BDDAssertions
ABDDAssertions
which allows to blend assertions with other libraries when the name 'then
' cause clash.Fields inherited from interface org.assertj.core.api.InstanceOfAssertFactories
ARRAY, ARRAY_2D, 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_2D_ARRAY, BOOLEAN_ARRAY, BYTE, BYTE_2D_ARRAY, BYTE_ARRAY, CHAR_2D_ARRAY, CHAR_ARRAY, CHAR_SEQUENCE, CHARACTER, CLASS, COLLECTION, COMPLETABLE_FUTURE, COMPLETION_STAGE, DATE, DOUBLE, DOUBLE_2D_ARRAY, DOUBLE_ARRAY, DOUBLE_PREDICATE, DOUBLE_STREAM, DURATION, FILE, FLOAT, FLOAT_2D_ARRAY, FLOAT_ARRAY, FUTURE, INPUT_STREAM, INSTANT, INT_2D_ARRAY, INT_ARRAY, INT_PREDICATE, INT_STREAM, INTEGER, ITERABLE, ITERATOR, LIST, LOCAL_DATE, LOCAL_DATE_TIME, LOCAL_TIME, LONG, LONG_2D_ARRAY, LONG_ADDER, LONG_ARRAY, LONG_PREDICATE, LONG_STREAM, MAP, MATCHER, OFFSET_DATE_TIME, OFFSET_TIME, OPTIONAL, OPTIONAL_DOUBLE, OPTIONAL_INT, OPTIONAL_LONG, PATH, PERIOD, PREDICATE, SHORT, SHORT_2D_ARRAY, SHORT_ARRAY, SPLITERATOR, STREAM, STRING, STRING_BUFFER, STRING_BUILDER, THROWABLE, URI_TYPE, URL_TYPE, ZONED_DATE_TIME
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Condition
<T> Creates a newAllOf
static <T> Condition
<T> Creates a newAllOf
static <T> ThrowingConsumer
<T> allOf
(ThrowingConsumer<? super T>... consumers) Create a new
that delegates the evaluation of the given consumers toThrowingConsumer
AbstractAssert.satisfies(ThrowingConsumer[])
.static <T> Condition
<T> Creates a newAnyOf
static <T> Condition
<T> Only delegate toAnyOf.anyOf(Condition...)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useAnyOf
if you prefer).static <T> ThrowingConsumer
<T> anyOf
(ThrowingConsumer<? super T>... consumers) Create a new
that delegates the evaluation of the given consumers toThrowingConsumer
AbstractAssert.satisfiesAnyOf(ThrowingConsumer[])
.static <T,
ASSERT extends AbstractAssert<?, ?>>
InstanceOfAssertFactory<T, ASSERT> as
(InstanceOfAssertFactory<T, ASSERT> assertFactory) A syntax sugar to write fluent assertion with methods having anInstanceOfAssertFactory
parameter.static 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 useIndex
if you prefer).static TemporalUnitOffset
byLessThan
(long value, TemporalUnit unit) Assertions entry point forTemporalUnitOffset
with strict less than condition to use withisCloseTo
temporal assertions.byLessThan
(Byte value) Assertions entry point for ByteOffset
to use with isCloseTo assertions.byLessThan
(Double value) Build astrict Offset
to use withAbstractDoubleAssert.isCloseTo(double, Offset)
andAbstractDoubleAssert.isNotCloseTo(double, Offset)
assertions.byLessThan
(Float value) Alias forAssertions.offset(Float)
to use with isCloseTo assertions.byLessThan
(Integer value) byLessThan
(Long value) byLessThan
(Short value) Assertions entry point for ShortOffset
to use with isCloseTo assertions.static Offset
<BigDecimal> byLessThan
(BigDecimal value) Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.static Offset
<BigInteger> byLessThan
(BigInteger value) Assertions entry point for BigIntegerOffset
to use with isCloseTo assertions.static Exception
catchException
(ThrowableAssert.ThrowingCallable shouldRaiseException) Allows catching an instance ofException
.static IllegalArgumentException
catchIllegalArgumentException
(ThrowableAssert.ThrowingCallable shouldRaiseIllegalArgumentException) Allows catching an instance ofIllegalArgumentException
.static IllegalStateException
catchIllegalStateException
(ThrowableAssert.ThrowingCallable shouldRaiseIllegalStateException) Allows catching an instance ofIllegalStateException
.static IndexOutOfBoundsException
catchIndexOutOfBoundsException
(ThrowableAssert.ThrowingCallable shouldRaiseIndexOutOfBoundException) Allows catching an instance ofIndexOutOfBoundsException
.static IOException
catchIOException
(ThrowableAssert.ThrowingCallable shouldRaiseIOException) Allows catching an instance ofIOException
.static NullPointerException
catchNullPointerException
(ThrowableAssert.ThrowingCallable shouldRaiseNullPointerException) Allows catching an instance ofNullPointerException
.static ReflectiveOperationException
catchReflectiveOperationException
(ThrowableAssert.ThrowingCallable shouldRaiseReflectiveOperationException) Allows catching an instance ofReflectiveOperationException
.static RuntimeException
catchRuntimeException
(ThrowableAssert.ThrowingCallable shouldRaiseRuntimeException) Allows catching an instance ofRuntimeException
.static Throwable
catchThrowable
(ThrowableAssert.ThrowingCallable shouldRaiseThrowable) Allows catching aThrowable
more easily when used with Java 8 lambdas.static <THROWABLE extends Throwable>
THROWABLEcatchThrowableOfType
(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, Class<THROWABLE> type) Allows catching aThrowable
of a specific type.static String
Loads the text content of a file with the default character set, so that it can be passed toAssertions.assertThat(String)
.static String
Loads the text content of a file, so that it can be passed toAssertions.assertThat(String)
.static String
Loads the text content of a file, so that it can be passed toAssertions.assertThat(String)
.static String
Loads the text content of a URL with the default character set, so that it can be passed toAssertions.assertThat(String)
.static String
Loads the text content of a URL, so that it can be passed toAssertions.assertThat(String)
.static String
Loads the text content of a URL, so that it can be passed toAssertions.assertThat(String)
.static <T> DoesNotHave
<T> doesNotHave
(Condition<? super T> condition) Creates a new
.DoesNotHave
static <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 useMapEntry
if you prefer).static 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 useProperties
if you prefer).static <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 useProperties
if you prefer).static <T> T
Throws anAssertionError
with the given message.static <T> T
Throws anAssertionError
with the given message built asString.format(String, Object...)
.static <T> T
Throws anAssertionError
with the given message and with theThrowable
that caused the failure.static <F,
T> Function <F, T> A syntax sugar to write fluent assertion usingAbstractObjectAssert.returns(Object, Function)
andAbstractObjectAssert.doesNotReturn(Object, Function)
.static InFilter
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches one of the given values.Loads the text content of a file into a list of strings with the default charset, each string corresponding to a line.Loads the text content of a file into a list of strings, each string corresponding to a line.Loads the text content of a file into a list of strings, each string corresponding to a line.Loads the text content of a URL into a list of strings with the default charset, each string corresponding to a line.Loads the text content of a URL into a list of strings, each string corresponding to a line.Loads the text content of a URL into a list of strings, each string corresponding to a line.Loads the text content of a file at a given path into a list of strings with the default charset, each string corresponding to a line.Loads the text content of a file at a given path into a list of strings, each string corresponding to a line.Loads the text content of a file at a given path into a list of strings, each string corresponding to a line.static NotFilter
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches does not match the given value.static <T> Not
<T> Creates a new
.Not
static NotInFilter
Create aFilterOperator
to 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.static 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)
.static 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)
.static <T> void
registerFormatterForType
(Class<T> type, Function<T, String> formatter) Assertions error messages uses aRepresentation
to format the different types involved, using this method you can control the formatting of a given type by providing a specific formatter.static void
setAllowComparingPrivateFields
(boolean allowComparingPrivateFields) Globally sets whether the use of private fields is allowed for comparison.static void
setAllowExtractingPrivateFields
(boolean allowExtractingPrivateFields) Globally sets whether
andIterableAssert#extracting(String)
should be allowed to extract private fields, if not and they try it fails with exception.ObjectArrayAssert#extracting(String)
static void
setDescriptionConsumer
(Consumer<Description> descriptionConsumer) All assertions description will be consumed by the givenConsumer<Description>
allowing for example to record them in a file.static void
setExtractBareNamePropertyMethods
(boolean barenamePropertyMethods) Globally sets whether the extractor considers bare-named property methods likeString name()
.static 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).static void
setMaxElementsForPrinting
(int maxElementsForPrinting) Sets the maximum number of elements to display in error messages for iterables, arrays and map .static void
setMaxLengthForSingleLineDescription
(int maxLengthForSingleLineDescription) In error messages, sets the threshold when iterable/array formatting will be on one line (if their String description length <= this parameter) or it will be formatted with one element per line.static void
setMaxStackTraceElementsDisplayed
(int maxStackTraceElementsDisplayed) Sets how many stacktrace elements are included inThrowable
representation (by default this set to 3).static void
setPrintAssertionsDescription
(boolean printAssertionsDescription) Enable/disable printing assertions description to the console (disabled by default).static void
setRemoveAssertJRelatedElementsFromStackTrace
(boolean removeAssertJRelatedElementsFromStackTrace) Sets whether we remove elements related to AssertJ from assertion error stack trace.static <T> T
shouldHaveThrown
(Class<? extends Throwable> throwableClass) Throws anAssertionError
with a message explaining that aThrowable
of given class was expected to be thrown but had not been.static AbstractBooleanAssert
<?> then
(boolean actual) Creates a new instance of
.BooleanAssert
static AbstractBooleanArrayAssert
<?> then
(boolean[] actual) Creates a new instance of
.BooleanArrayAssert
static Boolean2DArrayAssert
then
(boolean[][] actual) Creates a new instance of
.Boolean2DArrayAssert
static AbstractByteAssert
<?> then
(byte actual) Creates a new instance of
.ByteAssert
static AbstractByteArrayAssert
<?> then
(byte[] actual) Creates a new instance of
.ByteArrayAssert
static Byte2DArrayAssert
then
(byte[][] actual) Creates a new instance of
.Byte2DArrayAssert
static AbstractCharacterAssert
<?> then
(char actual) Creates a new instance of
.CharacterAssert
static AbstractCharArrayAssert
<?> then
(char[] actual) Creates a new instance of
.CharArrayAssert
static Char2DArrayAssert
then
(char[][] actual) Creates a new instance of
.Char2DArrayAssert
static AbstractDoubleAssert
<?> then
(double actual) Creates a new instance of
.DoubleAssert
static AbstractDoubleArrayAssert
<?> then
(double[] actual) Creates a new instance of
.DoubleArrayAssert
static Double2DArrayAssert
then
(double[][] actual) Creates a new instance of
.Double2DArrayAssert
static AbstractFloatAssert
<?> then
(float actual) Creates a new instance of
.FloatAssert
static AbstractFloatArrayAssert
<?> then
(float[] actual) Creates a new instance of
.FloatArrayAssert
static Float2DArrayAssert
then
(float[][] actual) Creates a new instance of
.Float2DArrayAssert
static AbstractIntegerAssert
<?> then
(int actual) Creates a new instance of
.IntegerAssert
static AbstractIntArrayAssert
<?> then
(int[] actual) Creates a new instance of
.IntArrayAssert
static Int2DArrayAssert
then
(int[][] actual) Creates a new instance of
.Int2DArrayAssert
static AbstractLongAssert
<?> then
(long actual) Creates a new instance of
.LongAssert
static AbstractLongArrayAssert
<?> then
(long[] actual) Creates a new instance of
.LongArrayAssert
static Long2DArrayAssert
then
(long[][] actual) Creates a new instance of
.Long2DArrayAssert
static AbstractShortAssert
<?> then
(short actual) Creates a new instance of
.ShortAssert
static AbstractShortArrayAssert
<?> then
(short[] actual) Creates a new instance of
.ShortArrayAssert
static Short2DArrayAssert
then
(short[][] actual) Creates a new instance of
.Short2DArrayAssert
static <ACTUAL extends Iterable<? extends ELEMENT>,
ELEMENT, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>>
ClassBasedNavigableIterableAssert<?, ACTUAL, ELEMENT, ELEMENT_ASSERT> Creates a new instance of
allowing to navigate to anyClassBasedNavigableIterableAssert
Iterable
element in order to perform assertions on it.static AbstractFileAssert
<?> Creates a new instance of
.FileAssert
static AbstractInputStreamAssert
<?, ? extends InputStream> then
(InputStream actual) Creates a new instance of
.InputStreamAssert
static AbstractBooleanAssert
<?> Creates a new instance of
.BooleanAssert
static AbstractByteAssert
<?> Creates a new instance of
.ByteAssert
static AbstractCharacterAssert
<?> Creates a new instance of
.CharacterAssert
static AbstractCharSequenceAssert
<?, ? extends CharSequence> then
(CharSequence actual) Creates a new instance of
.CharSequenceAssert
static ClassAssert
Creates a new instance of
.ClassAssert
static AbstractDoubleAssert
<?> Creates a new instance of
.DoubleAssert
static AbstractFloatAssert
<?> Creates a new instance of
.FloatAssert
static AbstractIntegerAssert
<?> Creates a new instance of
.IntegerAssert
static <ACTUAL extends Iterable<? extends ELEMENT>,
ELEMENT, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>>
FactoryBasedNavigableIterableAssert<?, ACTUAL, ELEMENT, ELEMENT_ASSERT> then
(Iterable<? extends ELEMENT> actual, AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory) Creates a new instance of
allowing to navigate to anyFactoryBasedNavigableIterableAssert
Iterable
element in order to perform assertions on it.static <T> IterableAssert
<T> Creates a new instance of
.IterableAssert
static AbstractLongAssert
<?> Creates a new instance of
.LongAssert
static AbstractShortAssert
<?> Creates a new instance of
.ShortAssert
static AbstractStringAssert
<?> Creates a new instance of
.StringAssert
static AbstractCharSequenceAssert
<?, ? extends CharSequence> then
(StringBuffer actual) Creates a new instance of
from aCharSequenceAssert
StringBuffer
.static AbstractCharSequenceAssert
<?, ? extends CharSequence> then
(StringBuilder actual) Creates a new instance of
from aCharSequenceAssert
StringBuilder
.static AbstractBigDecimalAssert
<?> then
(BigDecimal actual) Creates a new instance of
.BigDecimalAssert
static AbstractBigIntegerAssert
<?> then
(BigInteger actual) Creates a new instance of
.BigIntegerAssert
static AbstractUriAssert
<?> Creates a new instance of
.UriAssert
static AbstractUrlAssert
<?> Creates a new instance of
.UrlAssert
static AbstractPathAssert
<?> Creates a new instance ofPathAssert
static AbstractDurationAssert
<?> Creates a new instance of
.DurationAssert
static AbstractInstantAssert
<?> Creates a new instance of
.InstantAssert
static AbstractLocalDateAssert
<?> Creates a new instance of
.LocalDateAssert
static AbstractLocalDateTimeAssert
<?> then
(LocalDateTime actual) Creates a new instance of
.LocalDateTimeAssert
static AbstractLocalTimeAssert
<?> Creates a new instance of
.LocalTimeAssert
static AbstractOffsetDateTimeAssert
<?> then
(OffsetDateTime actual) Creates a new instance of
.OffsetTimeAssert
static AbstractOffsetTimeAssert
<?> then
(OffsetTime actual) Creates a new instance of
.OffsetTimeAssert
static AbstractPeriodAssert
<?> Creates a new instance of
.PeriodAssert
static AbstractZonedDateTimeAssert
<?> then
(ZonedDateTime actual) Creates a new instance of
.ZonedDateTimeAssert
static <E> AbstractCollectionAssert
<?, Collection<? extends E>, E, ObjectAssert<E>> then
(Collection<? extends E> actual) Creates a new instance of
.CollectionAssert
static AtomicBooleanAssert
then
(AtomicBoolean actual) Create assertion forAtomicBoolean
.static AtomicIntegerAssert
then
(AtomicInteger actual) Create assertion forAtomicInteger
.static AtomicIntegerArrayAssert
then
(AtomicIntegerArray actual) Create assertion forAtomicIntegerArray
.static <OBJECT> AtomicIntegerFieldUpdaterAssert
<OBJECT> then
(AtomicIntegerFieldUpdater<OBJECT> actual) Create assertion forAtomicIntegerFieldUpdater
.static AtomicLongAssert
then
(AtomicLong actual) Create assertion forAtomicLong
.static AtomicLongArrayAssert
then
(AtomicLongArray actual) Create assertion forAtomicLongArray
.static <OBJECT> AtomicLongFieldUpdaterAssert
<OBJECT> then
(AtomicLongFieldUpdater<OBJECT> actual) Create assertion forAtomicLongFieldUpdater
.static <VALUE> AtomicMarkableReferenceAssert
<VALUE> then
(AtomicMarkableReference<VALUE> actual) Create assertion forAtomicMarkableReference
.static <VALUE> AtomicReferenceAssert
<VALUE> then
(AtomicReference<VALUE> actual) Create assertion forAtomicReference
.static <ELEMENT> AtomicReferenceArrayAssert
<ELEMENT> then
(AtomicReferenceArray<ELEMENT> actual) Create assertion forAtomicReferenceArray
.static <FIELD,
OBJECT>
AtomicReferenceFieldUpdaterAssert<FIELD, OBJECT> then
(AtomicReferenceFieldUpdater<OBJECT, FIELD> actual) Create assertion forAtomicReferenceFieldUpdater
.static <VALUE> AtomicStampedReferenceAssert
<VALUE> then
(AtomicStampedReference<VALUE> actual) Create assertion forAtomicStampedReference
.static LongAdderAssert
Create assertion forLongAdder
.static <RESULT> CompletableFutureAssert
<RESULT> then
(CompletableFuture<RESULT> future) Create assertion forCompletableFuture
.static <RESULT> CompletableFutureAssert
<RESULT> then
(CompletionStage<RESULT> actual) Create assertion forCompletionStage
by converting it to aCompletableFuture
and returning aCompletableFutureAssert
.static <RESULT> FutureAssert
<RESULT> Creates a new instance ofFutureAssert
static AbstractDateAssert
<?> Creates a new instance of
.DateAssert
static DoublePredicateAssert
then
(DoublePredicate actual) Create assertion forDoublePredicate
.static IntPredicateAssert
then
(IntPredicate actual) Create assertion forIntPredicate
.static LongPredicateAssert
then
(LongPredicate actual) Create assertion forLongPredicate
.static <T> PredicateAssert
<T> Create assertion forPredicate
.static <T> IteratorAssert
<T> Creates a new instance of
.IteratorAssert
static <ELEMENT,
ACTUAL extends List<? extends ELEMENT>, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>>
ClassBasedNavigableListAssert<?, ACTUAL, ELEMENT, ELEMENT_ASSERT> Creates a new instance of
allowing to navigate to anyClassBasedNavigableListAssert
List
element in order to perform assertions on it.static <ACTUAL extends List<? extends ELEMENT>,
ELEMENT, ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>>
FactoryBasedNavigableListAssert<?, ACTUAL, ELEMENT, ELEMENT_ASSERT> then
(List<? extends ELEMENT> actual, AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory) Creates a new instance of
allowing to navigate to anyFactoryBasedNavigableListAssert
List
element in order to perform assertions on it.static <T> ListAssert
<T> Creates a new instance of
.ListAssert
static <K,
V> MapAssert <K, V> Creates a new instance of
.MapAssert
static <VALUE> OptionalAssert
<VALUE> Create assertion forOptional
.static OptionalDoubleAssert
then
(OptionalDouble optional) Create assertion forOptionalDouble
.static OptionalIntAssert
then
(OptionalInt optional) Create assertion forOptionalInt
.static OptionalLongAssert
then
(OptionalLong optional) Create assertion forOptionalLong
.static MatcherAssert
Create assertion forMatcher
static <ELEMENT> SpliteratorAssert
<ELEMENT> then
(Spliterator<ELEMENT> actual) Creates a new instance of
from the givenSpliteratorAssert
Spliterator
.static ListAssert
<Double> then
(DoubleStream actual) Creates a new instance of
from the givenListAssert
DoubleStream
.static ListAssert
<Integer> Creates a new instance of
from the givenListAssert
IntStream
.static ListAssert
<Long> then
(LongStream actual) Creates a new instance of
from the givenListAssert
LongStream
.static <ELEMENT> ListAssert
<ELEMENT> Creates a new instance of
from the givenListAssert
Stream
.static <T> T
then
(AssertProvider<T> component) Delegates the creation of theAssert
to theAssertProvider.assertThat()
of the given component.static <T extends Comparable<? super T>>
AbstractComparableAssert<?, T> then
(T actual) Creates a new instance of
with standard comparison semantics.GenericComparableAssert
static <T> ObjectArrayAssert
<T> then
(T[] actual) Creates a new instance of
.ObjectArrayAssert
static <T> Object2DArrayAssert
<T> then
(T[][] actual) Creates a new instance of
.Object2DArrayAssert
static AbstractCharSequenceAssert
<?, ? extends CharSequence> thenCharSequence
(CharSequence actual) Creates a new instance of
.CharSequenceAssert
static AbstractThrowableAssert
<?, ? extends Throwable> thenCode
(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable) Allows to capture and then assert on aThrowable
more easily when used with Java 8 lambdas.static <E> AbstractCollectionAssert
<?, Collection<? extends E>, E, ObjectAssert<E>> thenCollection
(Collection<? extends E> actual) Creates a new instance of
.CollectionAssert
static <T> AbstractUniversalComparableAssert
<?, T> thenComparable
(Comparable<T> actual) Creates a new instance of
with standard comparison semantics.UniversalComparableAssert
static ThrowableTypeAssert
<Exception> Alias forthenExceptionOfType(Class)
forException
.static <T extends Throwable>
ThrowableTypeAssert<T> thenExceptionOfType
(Class<? extends T> exceptionType) Entry point to check that an exception of type T is thrown by a giventhrowingCallable
which allows to chain assertions on the thrown exception.Alias forthenExceptionOfType(Class)
forIllegalArgumentException
.Alias forthenExceptionOfType(Class)
forIllegalStateException
.Alias forthenExceptionOfType(Class)
forIndexOutOfBoundsException
.static ThrowableTypeAssert
<IOException> Alias forthenExceptionOfType(Class)
forIOException
.static <ELEMENT> IterableAssert
<ELEMENT> thenIterable
(Iterable<? extends ELEMENT> actual) Creates a new instance of
.IterableAssert
static <ELEMENT> IteratorAssert
<ELEMENT> thenIterator
(Iterator<? extends ELEMENT> actual) Creates a new instance of
.IteratorAssert
static <ELEMENT> ListAssert
<ELEMENT> Creates a new instance of
.ListAssert
static NotThrownAssert
Entry point to check that no exception of any type is thrown by a giventhrowingCallable
.Alias forthenExceptionOfType(Class)
forNullPointerException
.static <T> ObjectAssert
<T> thenObject
(T actual) Creates a new instance of
for any object.ObjectAssert
static AbstractPathAssert
<?> Creates a new instance ofPathAssert
static <T> PredicateAssert
<T> thenPredicate
(Predicate<T> actual) Create assertion forPredicate
.Alias forthenExceptionOfType(Class)
forReflectiveOperationException
.static ThrowableTypeAssert
<RuntimeException> Alias forthenExceptionOfType(Class)
forRuntimeException
.static <ELEMENT> ListAssert
<ELEMENT> thenStream
(Stream<? extends ELEMENT> actual) Creates a new instance of
from the givenListAssert
Stream
.static AbstractThrowableAssert
<?, ? extends Throwable> thenThrownBy
(ThrowableAssert.ThrowingCallable shouldRaiseThrowable) Allows to capture and then assert on aThrowable
(easier done with lambdas).static AbstractThrowableAssert
<?, ? extends Throwable> thenThrownBy
(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, String description, Object... args) Allows to capture and then assert on aThrowable
likethenThrownBy(ThrowingCallable)
but this method let you set the assertion description the same way you do withas(String, Object...)
.static AbstractThrowableAssert
<?, ? extends Throwable> thenThrownBy
(ThrowableAssert.ThrowingCallableWithValue shouldRaiseThrowable) Similar tothenThrownBy(ThrowingCallable)
, but when the called code returns a value instead of throwing, the assertion error shows the returned value to help understand what went wrong.static AbstractThrowableAssert
<?, ? extends Throwable> thenThrownBy
(ThrowableAssert.ThrowingCallableWithValue shouldRaiseThrowable, String description, Object... args) Similar tothenThrownBy(ThrowingCallable, String, Object...)
, but when the called code returns a value instead of throwing, the assertion error shows the returned value to help understand what went wrong.static <T> ObjectAssert
<T> Uses the given instance as the instance under test for all the assertions expressed as the passedConsumer
s.static Tuple
Utility method to build nicely aTuple
when working withAbstractIterableAssert.extracting(String...)
orAbstractObjectArrayAssert.extracting(String...)
static void
Remove all registered custom date formats => use only the defaults date formats to parse string as date.static void
Fallback to useStandardRepresentation
to revert the effect of callinguseRepresentation(Representation)
.static void
useRepresentation
(Representation customRepresentation) Register aRepresentation
that will be used in all following assertions.static TemporalUnitOffset
within
(long value, TemporalUnit unit) Assertions entry point forTemporalUnitOffset
with less than or equal condition to use with isCloseTo temporal assertions.Assertions entry point for ByteOffset
to use with isCloseTo assertions.Builds anOffset
to use withisCloseTo
assertions.Builds anOffset
to use with isCloseTo assertions.Assertions entry point for IntegerOffset
to use with isCloseTo assertions.Assertions entry point for ShortOffset
to use with isCloseTo assertions.static Offset
<BigDecimal> within
(BigDecimal value) Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.static Offset
<BigInteger> within
(BigInteger value) Assertions entry point for BigIntegerOffset
to use with isCloseTo assertions.static Percentage
withinPercentage
(Double value) Assertions entry point for DoublePercentage
to use with isCloseTo assertions for percentages.static Percentage
withinPercentage
(Integer value) Assertions entry point for IntegerPercentage
to use with isCloseTo assertions for percentages.static Percentage
withinPercentage
(Long value) Assertions entry point for LongPercentage
to use with isCloseTo assertions for percentages.static Duration
withMarginOf
(Duration allowedDifference) Syntactic sugar method to use withAbstractDurationAssert.isCloseTo(Duration, Duration)
assertion.withPrecision
(Double value) Builds anOffset
to use with real number assertions.withPrecision
(Float value) Builds anOffset
to use with real number assertions.Methods inherited from class org.assertj.core.api.Assertions
assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThat, assertThatCharSequence, assertThatCode, assertThatCollection, assertThatComparable, assertThatException, assertThatExceptionOfType, assertThatIllegalArgumentException, assertThatIllegalStateException, assertThatIndexOutOfBoundsException, assertThatIOException, assertThatIterable, assertThatIterator, assertThatList, assertThatNoException, assertThatNullPointerException, assertThatObject, assertThatPath, assertThatPredicate, assertThatReflectiveOperationException, assertThatRuntimeException, assertThatStream, assertThatThrownBy, assertThatThrownBy, assertThatThrownBy, assertThatThrownBy, assertWith, failBecauseExceptionWasNotThrown, filter, filter, offset, offset
-
Field Details
-
and
ABDDAssertions
which allows to blend assertions with other libraries when the name 'then
' cause clash.Examples:
import static org.assertj.core.api.BDDAssertions.and; import static org.mockito.BDDMockito.then; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; // suppress and.then warning: The static method BDDAssertions.then() should be accessed in a static way @SuppressWarnings("static-access") @Test public void bdd_assertions_with_bdd_mockito() { // GIVEN Person person = mock(Person.class) // WHEN person.ride(bike); person.ride(bike); // THEN // mockito then() then(person).should(times(2)).ride(bike); // use AssertJ and.then(person) as then(person) would clash with mockito then(person) and.then(person.hasBike()).isTrue(); }
Can also be used to add extra readability:
import static org.assertj.core.api.BDDAssertions.and; import static org.assertj.core.api.BDDAssertions.then; // suppress and.then warning: The static method BDDAssertions.then() should be accessed in a static way @SuppressWarnings("static-access") @Test public void bdd_assertions_with_and_field() { // ... then(person.hasBike()).isTrue() and.then(bike.isNew()).isFalse(); }
- Since:
- 3.14.0
-
-
Constructor Details
-
BDDAssertions
protected BDDAssertions()Creates a new
.BDDAssertions
-
-
Method Details
-
then
Create assertion forPredicate
.- Type Parameters:
T
- the type of the value contained in thePredicate
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.5.0
-
thenPredicate
Create assertion forPredicate
.Use this over
then(Predicate)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.- Type Parameters:
T
- the type of the value contained in thePredicate
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.23.0
-
then
Create assertion forIntPredicate
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.5.0
-
then
Create assertion forLongPredicate
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.5.0
-
then
Create assertion forDoublePredicate
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.5.0
-
then
Create assertion forOptional
.- Type Parameters:
VALUE
- the type of the value contained in theOptional
.- Parameters:
optional
- the actual value.- Returns:
- the created assertion object.
-
then
Create assertion forOptionalInt
.- Parameters:
optional
- the actual value.- Returns:
- the created assertion object.
-
then
Create assertion forOptionalLong
.- Parameters:
optional
- the actual value.- Returns:
- the created assertion object.
-
then
Create assertion forMatcher
- Parameters:
actual
- the actual matcher- Returns:
- the created assertion object.
-
then
Create assertion forOptionalDouble
.- Parameters:
optional
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.BigDecimalAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.BigIntegerAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
then
Creates a new instance of
.BooleanAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.BooleanAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.BooleanArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Boolean2DArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.ByteAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.ByteAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.ByteArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Byte2DArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.CharacterAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.CharArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Char2DArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.CharacterAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.ClassAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
with standard comparison semantics.GenericComparableAssert
- Type Parameters:
T
- the actual type- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
thenComparable
Creates a new instance of
with standard comparison semantics.UniversalComparableAssert
Use this over
then(Comparable)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.- Type Parameters:
T
- the type of actual.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.23.0
-
then
Creates a new instance of
.IterableAssert
- Type Parameters:
T
- the actual elements type- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
thenIterable
Creates a new instance of
.IterableAssert
Use this over
then(Iterable)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.- Type Parameters:
ELEMENT
- the type of elements.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.23.0
-
then
Creates a new instance of
.IteratorAssert
Breaking change in version 3.12.0: this method does not return anymore an
IterableAssert
but anIteratorAssert
.
In order to access assertions fromIterableAssert
, useAbstractIteratorAssert.toIterable()
.IteratorAssert
instances have limited assertions because it does not consume iterator's elements.Examples:
Iterator<String> bestBasketBallPlayers = getBestBasketBallPlayers(); then(bestBasketBallPlayers).hasNext() // Iterator assertion .toIterable() // switch to Iterable assertions .contains("Jordan", "Magic", "Lebron"); // Iterable assertion
- Type Parameters:
T
- the actual elements type- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
thenIterator
Creates a new instance of
.IteratorAssert
Use this over
then(Iterator)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.- Type Parameters:
ELEMENT
- the type of elements.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.23.0
-
then
public static <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT, FactoryBasedNavigableIterableAssert<?,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> ACTUAL, thenELEMENT, ELEMENT_ASSERT> (Iterable<? extends ELEMENT> actual, AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory) Creates a new instance of
allowing to navigate to anyFactoryBasedNavigableIterableAssert
Iterable
element in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the
ELEMENT_ASSERT
parameter of the givenAssertFactory<ELEMENT, ELEMENT_ASSERT>
(AssertJ can't figure it out because of Java type erasure).Example with
String
element 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() then(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.
-
then
public static <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT, ClassBasedNavigableIterableAssert<?,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> ACTUAL, thenELEMENT, ELEMENT_ASSERT> (ACTUAL actual, Class<ELEMENT_ASSERT> assertClass) Creates a new instance of
allowing to navigate to anyClassBasedNavigableIterableAssert
Iterable
element 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
String
element assertions:Iterable<String> hobbits = newHashSet("frodo", "sam", "pippin"); // assertion succeeds with String assertions chained after first() then(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.
-
then
public static <ACTUAL extends List<? extends ELEMENT>,ELEMENT, FactoryBasedNavigableListAssert<?,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> ACTUAL, thenELEMENT, ELEMENT_ASSERT> (List<? extends ELEMENT> actual, AssertFactory<ELEMENT, ELEMENT_ASSERT> assertFactory) Creates a new instance of
allowing to navigate to anyFactoryBasedNavigableListAssert
List
element in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the
ELEMENT_ASSERT
parameter of the givenAssertFactory<ELEMENT, ELEMENT_ASSERT>
(AssertJ can't figure it out because of Java type erasure).Example with
String
element 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() then(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.
-
then
public static <ELEMENT,ACTUAL extends List<? extends ELEMENT>, ClassBasedNavigableListAssert<?,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT, ELEMENT>> ACTUAL, thenELEMENT, ELEMENT_ASSERT> (List<? extends ELEMENT> actual, Class<ELEMENT_ASSERT> assertClass) Creates a new instance of
allowing to navigate to anyClassBasedNavigableListAssert
List
element 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
String
element assertions:List<String> hobbits = newArrayList("frodo", "sam", "pippin"); // assertion succeeds with String assertions chained after first() then(hobbits, StringAssert.class).first() .startsWith("fro") .endsWith("do");
- Type Parameters:
ELEMENT
- The actual elements typeACTUAL
- The actual 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.
-
then
Creates a new instance of
.DoubleAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.DoubleAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.DoubleArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Double2DArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.FileAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance ofPathAssert
- Parameters:
actual
- the path to test- Returns:
- the created assertion object
-
thenPath
Creates a new instance ofPathAssert
Use this over
then(Path)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.- Parameters:
actual
- the path to test- Returns:
- the created assertion object
- Since:
- 3.23.0
-
then
Creates a new instance ofFutureAssert
- Type Parameters:
RESULT
- the type of the value contained in theFuture
.- Parameters:
actual
- the future to test- Returns:
- the created assertion object
- Since:
- 2.7.0 / 3.7.0
-
then
Creates a new instance of
.InputStreamAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.FloatAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.FloatAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.FloatArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Float2DArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.IntegerAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.IntArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Int2DArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.IntegerAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
public static <E> AbstractCollectionAssert<?,Collection<? extends E>, thenE, ObjectAssert<E>> (Collection<? extends E> actual) Creates a new instance of
.CollectionAssert
- Type Parameters:
E
- the type of elements.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.21.0
-
thenCollection
public static <E> AbstractCollectionAssert<?,Collection<? extends E>, thenCollectionE, ObjectAssert<E>> (Collection<? extends E> actual) Creates a new instance of
.CollectionAssert
Use this over
then(Collection)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.- Type Parameters:
E
- the type of elements.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.23.0
-
then
Creates a new instance of
.ListAssert
- Type Parameters:
T
- the type of elements.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
thenList
Creates a new instance of
.ListAssert
Use this over
then(List)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.- Type Parameters:
ELEMENT
- the type of elements.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.23.0
-
then
Creates a new instance of
.LongAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.LongAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.LongArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Long2DArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
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.
-
then
Creates a new instance of
.ObjectArrayAssert
- Type Parameters:
T
- the actual's elements type.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Object2DArrayAssert
- Type Parameters:
T
- the actual's elements type.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.MapAssert
- 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.
-
then
Creates a new instance of
.ShortAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.ShortAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.ShortArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.Short2DArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.CharSequenceAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
thenCharSequence
public static AbstractCharSequenceAssert<?,? extends CharSequence> thenCharSequence(CharSequence actual) Creates a new instance of
.CharSequenceAssert
Use this over
then(CharSequence)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.25.0
-
then
Creates a new instance of
from aCharSequenceAssert
StringBuilder
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.11.0
-
then
Creates a new instance of
from aCharSequenceAssert
StringBuffer
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.11.0
-
then
Creates a new instance of
.StringAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.DateAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Create assertion forAtomicBoolean
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
then
Create assertion forAtomicInteger
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
then
Create assertion forAtomicIntegerArray
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
then
public static <OBJECT> AtomicIntegerFieldUpdaterAssert<OBJECT> then(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.
- Since:
- 2.7.0 / 3.7.0
-
then
Create assertion forLongAdder
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.16.0
-
then
Create assertion forAtomicLong
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
then
Create assertion forAtomicLongArray
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
then
public static <OBJECT> AtomicLongFieldUpdaterAssert<OBJECT> then(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.
- Since:
- 2.7.0 / 3.7.0
-
then
Create assertion forAtomicReference
.- Type Parameters:
VALUE
- the type of the value contained in theAtomicReference
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
then
public static <ELEMENT> AtomicReferenceArrayAssert<ELEMENT> then(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.
- Since:
- 2.7.0 / 3.7.0
-
then
public static <FIELD,OBJECT> AtomicReferenceFieldUpdaterAssert<FIELD,OBJECT> then(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.
- Since:
- 2.7.0 / 3.7.0
-
then
public static <VALUE> AtomicMarkableReferenceAssert<VALUE> then(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.
- Since:
- 2.7.0 / 3.7.0
-
then
public static <VALUE> AtomicStampedReferenceAssert<VALUE> then(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.
- Since:
- 2.7.0 / 3.7.0
-
then
Creates a new instance of
.ThrowableAssert
- Type Parameters:
T
- the type of the actual throwable.- Parameters:
actual
- the actual value.- Returns:
- the created assertion Throwable.
-
thenThrownBy
public static AbstractThrowableAssert<?,? extends Throwable> thenThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable) Allows to capture and then assert on aThrowable
(easier done with lambdas).Example :
If the provided@Test public void testException() { thenThrownBy(() -> { throw new Exception("boom!") }).isInstanceOf(Exception.class) .hasMessageContaining("boom"); }
ThrowableAssert.ThrowingCallable
does 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(ThrowingCallable)
as shown below:
Alternatively you can also use// assertion will fail but "display me" won't appear in the error thenThrownBy(() -> {}).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.ThrowingCallable
or lambda with the code that should raise the throwable.- Returns:
- the created
ThrowableAssert
.
-
thenThrownBy
public static AbstractThrowableAssert<?,? extends Throwable> thenThrownBy(ThrowableAssert.ThrowingCallableWithValue shouldRaiseThrowable) Similar tothenThrownBy(ThrowingCallable)
, but when the called code returns a value instead of throwing, the assertion error shows the returned value to help understand what went wrong.- Parameters:
shouldRaiseThrowable
- TheThrowableAssert.ThrowingCallableWithValue
or lambda with the code that should raise the throwable.- Returns:
- the created
ThrowableAssert
. - Since:
- 3.25.0
-
thenThrownBy
public static AbstractThrowableAssert<?,? extends Throwable> thenThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, String description, Object... args) Allows to capture and then assert on aThrowable
likethenThrownBy(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] thenThrownBy(() -> { throw new IOException("boom!") }, "Test explosive code") .isInstanceOf(IOException.class) .hasMessageContaining("boom"); }
ThrowingCallable
does 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 thenThrownBy(() -> {}).as("display me") .isInstanceOf(Exception.class); // assertion will fail AND "display me" will appear in the error message thenThrownBy(() -> {}, "display me").isInstanceOf(Exception.class);
- Parameters:
shouldRaiseThrowable
- TheThrowableAssert.ThrowingCallable
or 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
-
thenThrownBy
public static AbstractThrowableAssert<?,? extends Throwable> thenThrownBy(ThrowableAssert.ThrowingCallableWithValue shouldRaiseThrowable, String description, Object... args) Similar tothenThrownBy(ThrowingCallable, String, Object...)
, but when the called code returns a value instead of throwing, the assertion error shows the returned value to help understand what went wrong.- Parameters:
shouldRaiseThrowable
- TheThrowableAssert.ThrowingCallableWithValue
or lambda with the code that should raise the throwable.- Returns:
- the created
ThrowableAssert
. - Since:
- 3.25.0
-
thenCode
public static AbstractThrowableAssert<?,? extends Throwable> thenCode(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable) Allows to capture and then assert on aThrowable
more easily when used with Java 8 lambdas.Example :
If the providedThrowingCallable callable = () -> { throw new Exception("boom!"); }; // assertion succeeds thenCode(callable).isInstanceOf(Exception.class) .hasMessageContaining("boom"); // assertion fails thenCode(callable).doesNotThrowAnyException();
ThrowableAssert.ThrowingCallable
does 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(ThrowingCallable)
as shown below.ThrowingCallable doNothing = () -> { // do nothing }; // assertion fails and "display me" appears in the assertion error thenCode(doNothing).as("display me") .isInstanceOf(Exception.class); // assertion will fail AND "display me" will appear in the error Throwable thrown = catchThrowable(doNothing); thenCode(thrown).as("display me") .isInstanceOf(Exception.class);
This method was not named
then
because the java compiler reported it ambiguous when used directly with a lambda :(- Parameters:
shouldRaiseOrNotThrowable
- TheThrowableAssert.ThrowingCallable
or lambda with the code that should raise the throwable.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.7.0
-
thenObject
Creates a new instance of
for any object.ObjectAssert
This overload is useful, when an overloaded method of then(...) takes precedence over the generic
then(Object)
.Example:
Cast necessary because
then(List)
"forgets" actual type:
No cast needed, but also no additional list assertions:then(new LinkedList<>(asList("abc"))).matches(list -> ((Deque<String>) list).getFirst().equals("abc"));
thenObject(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
-
thenWith
Uses the given instance as the instance under test for all the assertions expressed as the passedConsumer
s.This is useful to avoid repeating getting the instance to test, a bit like a with block which turns the target into the equivalent of
this
(as in Groovy for example).Example:
thenWith(team.getPlayers().get(0).getStats(), stat -> assertThat(stats.pointPerGame).isGreaterThan(25.7), stat -> assertThat(stats.assistsPerGame).isGreaterThan(7.2), stat -> assertThat(stats.reboundsPerGame).isBetween(9, 12) );
thenWith
is variation ofAbstractAssert.satisfies(Consumer[])
hopefully easier to find for some users.- Type Parameters:
T
- the type of the actual value.- Parameters:
actual
- the actual value.requirements
- to assert on the actual object - must not be null.- Returns:
- the created assertion object.
- Since:
- 3.20.0
-
then
Creates a new instance of
.LocalDateAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.LocalDateTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.ZonedDateTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.LocalTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.OffsetTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.InstantAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.7.0
-
then
Creates a new instance of
.DurationAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.15.0
-
then
Creates a new instance of
.PeriodAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.17.0
-
then
Creates a new instance of
.UriAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.UrlAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
.OffsetTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Create assertion forCompletableFuture
.- Type Parameters:
RESULT
- the type of the value contained in theCompletableFuture
.- Parameters:
future
- the actual value.- Returns:
- the created assertion object.
-
then
Create assertion forCompletionStage
by converting it to aCompletableFuture
and returning aCompletableFutureAssert
.If the given
CompletionStage
is null, theCompletableFuture
in the returnedCompletableFutureAssert
will also be null.- Type Parameters:
RESULT
- the type of the value contained in theCompletionStage
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
then
Returns the given assertion. This method improves code readability by surrounding the given assertion withthen
.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.then then(button.isBlinking()).isTrue(); } void isNotBlinking() { // standard assertion from core Assertions.then then(button.isBlinking()).isFalse(); } }
then(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 then then(buttonAssert).isNotBlinking(); // same as : buttonAssert.isNotBlinking(); button.setBlinking(true); then(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.
-
then
Delegates the creation of theAssert
to theAssertProvider.assertThat()
of the given component.Read the comments on
AssertProvider
for an example of its usage.- Type Parameters:
T
- the AssertProvider wrapped type.- Parameters:
component
- the component that creates its own assert- Returns:
- the associated
Assert
of the given component
-
then
Creates a new instance of
from the givenListAssert
Stream
.Be aware that the
Stream
under test will be converted to aList
when an assertions require to inspect its content. Once this is done theStream
can't reused as it would have been consumed.Calling multiple methods on the returned
ListAssert
is safe as it only interacts with theList
built from theStream
.Examples:
// you can chain multiple assertions on the Stream as it is converted to a List then(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. then(Stream.of(1, 2, 3)).isEqualTo(Stream.of(1, 2, 3));
These assertions succeed as
isEqualTo
andisSameAs
checks 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); then(stream).isEqualTo(stream) .isSameAs(stream);
- Type Parameters:
ELEMENT
- the type of elements.- Parameters:
actual
- the actualStream
value.- Returns:
- the created assertion object.
-
thenStream
Creates a new instance of
from the givenListAssert
Stream
.Use this over
then(Stream)
in case of ambiguous method resolution when the object under test implements several interfaces Assertj providesthen
for.Be aware that the
Stream
under test will be converted to aList
when an assertions require to inspect its content. Once this is done theStream
can't reused as it would have been consumed.Calling multiple methods on the returned
ListAssert
is safe as it only interacts with theList
built from theStream
.Examples:
// you can chain multiple assertions on the Stream as it is converted to a List then(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. then(Stream.of(1, 2, 3)).isEqualTo(Stream.of(1, 2, 3));
These assertions succeed as
isEqualTo
andisSameAs
checks 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); then(stream).isEqualTo(stream) .isSameAs(stream);
- Type Parameters:
ELEMENT
- the type of elements.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.23.0
-
then
Creates a new instance of
from the givenListAssert
DoubleStream
.Be aware that the
DoubleStream
under test will be converted to aList
when an assertions require to inspect its content. Once this is done theDoubleStream
can't reused as it would have been consumed.Calling multiple methods on the returned
ListAssert
is safe as it only interacts with theList
built from theDoubleStream
.Examples:
// you can chain multiple assertions on the DoubleStream as it is converted to a List then(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. then(DoubleStream.of(1.0, 2.0, 3.0)).isEqualTo(DoubleStream.of(1.0, 2.0, 3.0));
These assertions succeed as
isEqualTo
andisSameAs
checks 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); then(stream).isEqualTo(stream) .isSameAs(stream);
- Parameters:
actual
- the actualDoubleStream
value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
from the givenListAssert
LongStream
.Be aware that the
LongStream
under test will be converted to aList
when an assertions require to inspect its content. Once this is done theLongStream
can't reused as it would have been consumed.Calling multiple methods on the returned
ListAssert
is safe as it only interacts with theList
built from theLongStream
.Examples:
// you can chain multiple assertions on the LongStream as it is converted to a List then(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. then(LongStream.of(1, 2, 3)).isEqualTo(LongStream.of(1, 2, 3));
These assertions succeed as
isEqualTo
andisSameAs
checks 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); then(stream).isEqualTo(stream) .isSameAs(stream);
- Parameters:
actual
- the actualLongStream
value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
from the givenListAssert
IntStream
.Be aware that the
IntStream
under test will be converted to aList
when an assertions require to inspect its content. Once this is done theIntStream
can't reused as it would have been consumed.Calling multiple methods on the returned
ListAssert
is safe as it only interacts with theList
built from theIntStream
.Examples:
// you can chain multiple assertions on the IntStream as it is converted to a List then(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. then(IntStream.of(1, 2, 3)).isEqualTo(IntStream.of(1, 2, 3));
These assertions succeed as
isEqualTo
andisSameAs
checks 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); then(stream).isEqualTo(stream) .isSameAs(stream);
- Parameters:
actual
- the actualIntStream
value.- Returns:
- the created assertion object.
-
then
Creates a new instance of
from the givenSpliteratorAssert
Spliterator
. Example:Spliterator<Integer> spliterator = Stream.of(1, 2, 3).spliterator(); then(spliterator).hasCharacteristics(Spliterator.SIZED);
- Type Parameters:
ELEMENT
- the type of elements.- Parameters:
actual
- the spliterator to test.- Returns:
- the created assertion object.
- Since:
- 3.14.0
-
catchThrowable
Allows catching aThrowable
more easily when used with Java 8 lambdas.This caught
Throwable
can then be asserted.If you need to assert on the real type of Throwable caught (e.g. IOException), use
catchThrowableOfType(ThrowingCallable, Class)
.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
null
if none was raised by the callable. - Since:
- 3.20.0
- See Also:
-
catchThrowableOfType
public static <THROWABLE extends Throwable> THROWABLE catchThrowableOfType(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, Class<THROWABLE> type) Allows catching aThrowable
of a specific type.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
has the specified type and casts it making it convenient to perform subtype-specific assertions on it.Example:
class TextException extends Exception { int line; int column; public TextException(String msg, int line, int column) { super(msg); this.line = line; this.column = column; } } TextException textException = catchThrowableOfType(() -> { throw new TextException("boom!", 1, 5); }, TextException.class); // assertions succeed assertThat(textException).hasMessage("boom!"); assertThat(textException.line).isEqualTo(1); assertThat(textException.column).isEqualTo(5); // succeeds as catchThrowableOfType returns null when the code does not thrown any exceptions assertThat(catchThrowableOfType(() -> {}, Exception.class)).isNull(); // fails as TextException is not a RuntimeException catchThrowableOfType(() -> { throw new TextException("boom!", 1, 5); }, RuntimeException.class);
- Type Parameters:
THROWABLE
- theThrowable
type.- 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
null
if none was raised by the callable. - Since:
- 3.20.0
- See Also:
-
catchException
Allows catching an instance ofException
.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
is of typeException
and casts it making it convenient to perform subtype-specific assertions on it.Example:
Exception exception = catchException(() -> {throw new Exception("boom!");}); // assertions succeed assertThat(exception).hasMessage("boom!"); // succeeds as catchException returns null when the code does not throw any exceptions assertThat(catchException(() -> {})).isNull(); // fails as the thrown instance is not an Exception catchException(() -> {throw new Throwable("boom!");});
- Parameters:
shouldRaiseException
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.22.0
- See Also:
-
catchRuntimeException
public static RuntimeException catchRuntimeException(ThrowableAssert.ThrowingCallable shouldRaiseRuntimeException) Allows catching an instance ofRuntimeException
.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
is of typeRuntimeException
and casts it making it convenient to perform subtype-specific assertions on it.Example:
RuntimeException runtimeException = catchRuntimeException(() -> {throw new RuntimeException("boom!");}); // assertions succeed assertThat(runtimeException).hasMessage("boom!"); // succeeds as catchRuntimeException returns null when the code does not throw any exceptions assertThat(catchRuntimeException(() -> {})).isNull(); // fails as the thrown instance is not a RuntimeException catchRuntimeException(() -> {throw new Exception("boom!");});
- Parameters:
shouldRaiseRuntimeException
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.22.0
- See Also:
-
catchNullPointerException
public static NullPointerException catchNullPointerException(ThrowableAssert.ThrowingCallable shouldRaiseNullPointerException) Allows catching an instance ofNullPointerException
.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
is of typeRuntimeException
and casts it making it convenient to perform subtype-specific assertions on it.Example:
NullPointerException nullPointerException = catchNullPointerException(() -> {throw new NullPointerException("boom!");}); // assertions succeed assertThat(nullPointerException).hasMessage("boom!"); // succeeds as catchNullPointerException returns null when the code does not throw any exceptions assertThat(catchNullPointerException(() -> {})).isNull(); // fails as the thrown instance is not a NullPointerException catchNullPointerException(() -> {throw new Exception("boom!");});
- Parameters:
shouldRaiseNullPointerException
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.22.0
- See Also:
-
catchIllegalArgumentException
public static IllegalArgumentException catchIllegalArgumentException(ThrowableAssert.ThrowingCallable shouldRaiseIllegalArgumentException) Allows catching an instance ofIllegalArgumentException
.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
is of typeIllegalArgumentException
and casts it making it convenient to perform subtype-specific assertions on it.Example:
// fails as the thrown instance is not an IllegalArgumentException catchIllegalArgumentException(() -> {throw new Exception("boom!");});IllegalArgumentException illegalArgumentException = catchIllegalArgumentException(() -> {throw new IllegalArgumentException("boom!");}); // assertions succeed assertThat(illegalArgumentException).hasMessage("boom!"); // succeeds as catchNullPointerException returns null when the code does not throw any exceptions assertThat(catchIllegalArgumentException(() -> {})).isNull();
- Parameters:
shouldRaiseIllegalArgumentException
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.22.0
- See Also:
-
catchIOException
Allows catching an instance ofIOException
.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
is of typeIOException
and casts it making it convenient to perform subtype-specific assertions on it.Example:
IOException iOException = catchIOException(() -> {throw new IOException("boom!");}); // assertions succeed assertThat(iOException).hasMessage("boom!"); // succeeds as catchIOException returns null when the code does not throw any exceptions assertThat(catchIOException(() -> {})).isNull(); // fails as the thrown instance is not an IOException catchIOException(() -> {throw new Exception("boom!");});
- Parameters:
shouldRaiseIOException
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.22.0
- See Also:
-
catchReflectiveOperationException
public static ReflectiveOperationException catchReflectiveOperationException(ThrowableAssert.ThrowingCallable shouldRaiseReflectiveOperationException) Allows catching an instance ofReflectiveOperationException
.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
is of typeReflectiveOperationException
and casts it making it convenient to perform subtype-specific assertions on it.Example:
ReflectiveOperationException reflectiveOperationException = catchReflectiveOperationException(() -> {throw new ReflectiveOperationException("boom!");}); // assertions succeed assertThat(reflectiveOperationException).hasMessage("boom!"); // succeeds as catchReflectiveOperationException returns null when the code does not throw any exceptions assertThat(catchReflectiveOperationException(() -> {})).isNull(); // fails as the thrown instance is not an IOException catchReflectiveOperationException(() -> {throw new Exception("boom!");});
- Parameters:
shouldRaiseReflectiveOperationException
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.22.0
- See Also:
-
catchIllegalStateException
public static IllegalStateException catchIllegalStateException(ThrowableAssert.ThrowingCallable shouldRaiseIllegalStateException) Allows catching an instance ofIllegalStateException
.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
is of typeIllegalStateException
and casts it making it convenient to perform subtype-specific assertions on it.Example:
IllegalStateException illegalStateException = catchIllegalStateException(() -> {throw new IllegalStateException("boom!");}); // assertions succeed assertThat(illegalStateException).hasMessage("boom!"); // succeeds as catchReflectiveOperationException returns null when the code does not throw any exceptions assertThat(catchIllegalStateException(() -> {})).isNull(); // fails as the thrown instance is not an IOException catchIllegalStateException(() -> {throw new Exception("boom!");});
- Parameters:
shouldRaiseIllegalStateException
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.22.0
- See Also:
-
catchIndexOutOfBoundsException
public static IndexOutOfBoundsException catchIndexOutOfBoundsException(ThrowableAssert.ThrowingCallable shouldRaiseIndexOutOfBoundException) Allows catching an instance ofIndexOutOfBoundsException
.A call is made to
catchThrowable(ThrowingCallable)
, if no exception is thrown it returns null otherwise it checks that the caughtThrowable
is of typeIndexOutOfBoundsException
and casts it making it convenient to perform subtype-specific assertions on it.Example:
IndexOutOfBoundsException indexOutOfBoundsException = catchIndexOutOfBoundsException(() -> {throw new IndexOutOfBoundsException("boom!");}); // assertions succeed assertThat(indexOutOfBoundsException).hasMessage("boom!"); // succeeds as catchIndexOutOfBoundsException returns null when the code does not throw any exceptions assertThat(catchIndexOutOfBoundsException(() -> {})).isNull(); // fails as the thrown instance is not an IOException catchIndexOutOfBoundsException(() -> {throw new Exception("boom!");});
- Parameters:
shouldRaiseIndexOutOfBoundException
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.22.0
- See Also:
-
thenExceptionOfType
public static <T extends Throwable> ThrowableTypeAssert<T> thenExceptionOfType(Class<? extends T> exceptionType) Entry point to check that an exception of type T is thrown by a giventhrowingCallable
which allows to chain assertions on the thrown exception.Example:
This method is more or less the same ofthenExceptionOfType(IOException.class) .isThrownBy(() -> { throw new IOException("boom!"); }) .withMessage("boom!");
thenThrownBy(ThrowingCallable)
but in a more natural way.- Type Parameters:
T
- the exception type.- Parameters:
exceptionType
- the exception type class.- Returns:
- the created
ThrowableTypeAssert
.
-
thenNoException
Entry point to check that no exception of any type is thrown by a giventhrowingCallable
.Example:
This method is more or less the same ofthenNoException().isThrownBy(() -> { System.out.println("OK"); });
thenCode(...).doesNotThrowAnyException();
but in a more natural way.- Returns:
- the created
NotThrownAssert
. - Since:
- 3.17.0
-
thenNullPointerException
Alias forthenExceptionOfType(Class)
forNullPointerException
.- Returns:
- the created
ThrowableTypeAssert
.
-
thenIllegalArgumentException
Alias forthenExceptionOfType(Class)
forIllegalArgumentException
.- Returns:
- the created
ThrowableTypeAssert
.
-
thenIOException
Alias forthenExceptionOfType(Class)
forIOException
.- Returns:
- the created
ThrowableTypeAssert
.
-
thenIllegalStateException
Alias forthenExceptionOfType(Class)
forIllegalStateException
.- Returns:
- the created
ThrowableTypeAssert
.
-
thenException
Alias forthenExceptionOfType(Class)
forException
.- Returns:
- the created
ThrowableTypeAssert
. - Since:
- 3.23.0
-
thenIndexOutOfBoundsException
Alias forthenExceptionOfType(Class)
forIndexOutOfBoundsException
.- Returns:
- the created
ThrowableTypeAssert
. - Since:
- 3.23.0
-
thenReflectiveOperationException
Alias forthenExceptionOfType(Class)
forReflectiveOperationException
.- Returns:
- the created
ThrowableTypeAssert
. - Since:
- 3.23.0
-
thenRuntimeException
Alias forthenExceptionOfType(Class)
forRuntimeException
.- Returns:
- the created
ThrowableTypeAssert
. - Since:
- 3.23.0
-
setRemoveAssertJRelatedElementsFromStackTrace
public static void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace) Sets whether we remove elements related to AssertJ from assertion error stack trace.Default is true.
- Parameters:
removeAssertJRelatedElementsFromStackTrace
- flag.- Since:
- 3.20.0
-
fail
Throws anAssertionError
with 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.orElseGet(() -> fail("boom")));
. - Throws:
AssertionError
- with the given message.- Since:
- 3.20.0
-
fail
Throws anAssertionError
with 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.orElseGet(() -> fail("b%s", ""oom)));
. - Throws:
AssertionError
- with the given built message.- Since:
- 3.20.0
-
fail
Throws anAssertionError
with the given message and with theThrowable
that 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.orElseGet(() -> fail("boom", cause)));
. - Throws:
AssertionError
- with the given message and with theThrowable
that caused the failure.- Since:
- 3.20.0
-
shouldHaveThrown
Throws anAssertionError
with a message explaining that aThrowable
of 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.orElseGet(() -> shouldHaveThrown(IOException.class)));
. - Throws:
AssertionError
- with a message explaining that aThrowable
of given class was expected to be thrown but had not been.- Since:
- 3.20.0
-
setMaxLengthForSingleLineDescription
public static void setMaxLengthForSingleLineDescription(int maxLengthForSingleLineDescription) In error messages, sets the threshold when iterable/array formatting will be on one line (if their String description length <= this parameter) or it will be formatted with one element per line.The default value for maxLengthForSingleLineDescription is 80.
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.20.0
-
setMaxElementsForPrinting
public static void setMaxElementsForPrinting(int maxElementsForPrinting) Sets the maximum number of elements to display in error messages for iterables, arrays and map .Example with a value of
4
.The following array will be formatted entirely as it's length is <= 4:
whereas for this 6 elements array, only the first and last two elements are displayed (4 in total):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!", "The Lies of Locke Lamora", "Aux Ombres d’Abyme"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", ... "The Lies of Locke Lamora", "Aux Ombres d’Abyme"]
- Parameters:
maxElementsForPrinting
- the maximum elements that would be printed for iterables, arrays and maps.- Since:
- 3.20.0
-
setPrintAssertionsDescription
public static void setPrintAssertionsDescription(boolean printAssertionsDescription) Enable/disable printing assertions description to the console (disabled by default).The printed assertions description include all the successful assertions description and respectively the first failed one for standard assertions and all failed ones for soft assertions.
If you want to process the description differently, create a
Consumer<Description>
and register it withsetDescriptionConsumer(Consumer)
.- Parameters:
printAssertionsDescription
- whether to print assertions description.- Since:
- 3.20.0
-
setDescriptionConsumer
All assertions description will be consumed by the givenConsumer<Description>
allowing for example to record them in a file.The consumed descriptions include all the successful assertions description and respectively the first failed one for standard assertions and all failed ones for soft assertions.
To unset the descriptionConsumer, call
setDescriptionConsumer(null);
- Parameters:
descriptionConsumer
- theDescription
consumer- Since:
- 3.20.0
-
setMaxStackTraceElementsDisplayed
public static void setMaxStackTraceElementsDisplayed(int maxStackTraceElementsDisplayed) Sets how many stacktrace elements are included inThrowable
representation (by default this set to 3).Examples:
static class Test1 { static void boom() { Test2.boom2(); } static class Test2 { static void boom2() { throw new RuntimeException(); } } }
Test1.boom()
exception should be represented like this in error messages:java.lang.RuntimeException at org.assertj.core.presentation.Test1$Test2.boom2(StandardRepresentation_throwable_format_Test.java:35) at org.assertj.core.presentation.Test1.boom(StandardRepresentation_throwable_format_Test.java:40);java.lang.RuntimeException at org.assertj.core.presentation.Test1.lambda$1(StandardRepresentation_throwable_format_Test.java:63)org.assertj.core.util.Throwables_Description_Test$test1$test2.exception_layer_2(Throwables_Description_Test.java:24) ...(69 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed)org.assertj.core.util.Throwables_Description_Test$test1.exception_layer_1(Throwables_Description_Test.java:30)
- Parameters:
maxStackTraceElementsDisplayed
- the maximum number of lines for a stacktrace to be displayed on one throw.- Since:
- 3.20.0
- See Also:
-
extractProperty
Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).Typical usage is to chain
extractProperty
withfrom
method, 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.- Since:
- 3.20.0
-
extractProperty
Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).Typical usage is to chain
extractProperty
withfrom
method, 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.- Since:
- 3.20.0
-
tuple
Utility method to build nicely aTuple
when working withAbstractIterableAssert.extracting(String...)
orAbstractObjectArrayAssert.extracting(String...)
-
setAllowExtractingPrivateFields
public static void setAllowExtractingPrivateFields(boolean allowExtractingPrivateFields) Globally sets whether
andIterableAssert#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. Default is true.- Since:
- 3.20.0
-
setAllowComparingPrivateFields
public static 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)
false
and these methods try to compare private fields, it will fail with an exception.- Parameters:
allowComparingPrivateFields
- allow private fields comparison. Default is true.- Since:
- 3.20.0
-
-
setExtractBareNamePropertyMethods
public static 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- Since:
- 3.20.0
-
entry
Only delegate toMapEntry.entry(Object, Object)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useMapEntry
if you prefer).Typical usage is to call
entry
in MapAssertcontains
assertion, 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
. - Since:
- 3.20.0
-
atIndex
Only delegate toIndex.atIndex(int)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useIndex
if 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.- Since:
- 3.20.0
-
within
Builds anOffset
to use withisCloseTo
assertions.Typical usage :
assertThat(0.1).isCloseTo(0.0, within(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.20.0
-
withPrecision
Builds anOffset
to use with real number assertions.Typical usage :
assertThat(0.1).isEqualTo(0.0, withPrecision(0.1));
- Parameters:
value
- the required precision- Returns:
- the created
Offset
. - Throws:
NullPointerException
- if the given value isnull
.IllegalArgumentException
- if the given value is negative.- Since:
- 3.20.0
-
within
Builds anOffset
to use with isCloseTo assertions.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, within(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.20.0
-
withPrecision
Builds anOffset
to use with real number assertions.Typical usage :
assertThat(0.2f).isEqualTo(0.0f, withPrecision(0.2f));
- Parameters:
value
- the required precision- Returns:
- the created
Offset
. - Throws:
NullPointerException
- if the given value isnull
.IllegalArgumentException
- if the given value is negative.- Since:
- 3.20.0
-
within
Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.Typical usage :
assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), within(BigDecimal.ONE));
- 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.20.0
-
within
Assertions entry point for BigIntegerOffset
to use with isCloseTo assertions.Typical usage :
assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), within(new BigInteger("2")));
- Parameters:
value
- the allowed offset- Returns:
- the created
Offset
. - Throws:
NullPointerException
- if the given value isnull
.IllegalArgumentException
- if the given value is negative.- Since:
- 2.7.0 / 3.7.0, 3.20.0
-
within
Assertions entry point for ByteOffset
to 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.20.0
-
within
Assertions entry point for IntegerOffset
to 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.20.0
-
within
Assertions entry point for ShortOffset
to use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, within(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.20.0
-
within
Assertions entry point for LongOffset
to use withisCloseTo
assertions.Typical usage :
assertThat(5l).isCloseTo(7l, within(2l));
- 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.20.0
-
within
Assertions entry point forTemporalUnitOffset
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
- theTemporalUnit
of the offset- Returns:
- the created
Offset
. - Since:
- 3.20.0
-
withMarginOf
Syntactic sugar method to use withAbstractDurationAssert.isCloseTo(Duration, Duration)
assertion.Example:
assertThat(Duration.ofMinutes(2)).isCloseTo(Duration.ofMinutes(3), withMarginOf(Duration.ofMinutes(1)));
- Parameters:
allowedDifference
- the allowed differenceDuration
.- Returns:
- the given value.
- Since:
- 3.20.0
-
withinPercentage
Assertions entry point for DoublePercentage
to 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.20.0
-
withinPercentage
Assertions entry point for IntegerPercentage
to 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.20.0
-
withinPercentage
Assertions entry point for LongPercentage
to 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.20.0
-
byLessThan
Build astrict Offset
to use withAbstractDoubleAssert.isCloseTo(double, Offset)
andAbstractDoubleAssert.isNotCloseTo(double, Offset)
assertions.A strict offset implies a strict comparison which means that
isCloseTo
will fail when abs(actual - expected) == offset.Examples:
// assertion succeeds assertThat(8.1).isCloseTo(8.0, byLessThan(0.2)); // assertions fail assertThat(8.1).isCloseTo(8.0, byLessThan(0.1)); // strict comparison! assertThat(8.1).isCloseTo(8.0, byLessThan(0.01));
- 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.20.0
-
byLessThan
Alias forAssertions.offset(Float)
to use with isCloseTo assertions.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, byLessThan(0.5f));
- 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.20.0
-
byLessThan
Assertions entry point for BigDecimalOffset
to 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.20.0
-
byLessThan
Assertions entry point for BigIntegerOffset
to 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.20.0
-
byLessThan
Assertions entry point for ByteOffset
to use with isCloseTo assertions.Typical usage :
assertThat((byte) 10).isCloseTo((byte) 11, byLessThan((byte) 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.20.0
-
byLessThan
Assertions entry point for LongOffset
to use with strictisCloseTo
assertions.Typical usage :
assertThat(10).isCloseTo(12, 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.20.0
-
byLessThan
Assertions entry point for ShortOffset
to use with isCloseTo assertions.Typical usage :
assertThat((short) 10).isCloseTo((short) 11, byLessThan((short) 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.20.0
-
byLessThan
Assertions entry point for LongOffset
to use with strictisCloseTo
assertions.Typical usage :
assertThat(5l).isCloseTo(7l, byLessThan(3l));
- 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.20.0
-
byLessThan
Assertions entry point forTemporalUnitOffset
with strict less than condition to use withisCloseTo
temporal 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
- theTemporalUnit
of the offset.- Returns:
- the created
Offset
. - Since:
- 3.20.0
-
from
A syntax sugar to write fluent assertion usingAbstractObjectAssert.returns(Object, Function)
andAbstractObjectAssert.doesNotReturn(Object, Function)
.Example:
Jedi yoda = new Jedi("Yoda", "Green"); assertThat(yoda).returns("Yoda", from(Jedi::getName)) .returns(2.4, from(Jedi::getHeight)) .doesNotReturn(null, 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.20.0
-
as
public static <T,ASSERT extends AbstractAssert<?, InstanceOfAssertFactory<T,?>> ASSERT> as(InstanceOfAssertFactory<T, ASSERT> assertFactory) A syntax sugar to write fluent assertion with methods having anInstanceOfAssertFactory
parameter.Example:
Jedi yoda = new Jedi("Yoda", "Green"); assertThat(yoda).extracting(Jedi::getName, as(InstanceOfAssertFactories.STRING)) .startsWith("Yo");
- Type Parameters:
T
- the type to use for the cast.ASSERT
- the type of the resultingAssert
- Parameters:
assertFactory
- the factory which verifies the type and creates the newAssert
- Returns:
- same instance of
assertFactory
- Since:
- 3.20.0, 3.20.0
- See Also:
-
allOf
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
.- Since:
- 3.20.0
-
allOf
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
.- Since:
- 3.20.0
-
allOf
Create a new
that delegates the evaluation of the given consumers toThrowingConsumer
AbstractAssert.satisfies(ThrowingConsumer[])
.- Type Parameters:
T
- the type of object the given consumers accept- Parameters:
consumers
- the consumers to evaluate- Returns:
- the
ThrowingConsumer
instance - Since:
- 3.25.0
-
anyOf
Only delegate toAnyOf.anyOf(Condition...)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useAnyOf
if you prefer).Typical usage (
jedi
andsith
areCondition
) :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
. - Since:
- 3.20.0
-
anyOf
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
.- Since:
- 3.20.0
-
anyOf
Create a new
that delegates the evaluation of the given consumers toThrowingConsumer
AbstractAssert.satisfiesAnyOf(ThrowingConsumer[])
.- Type Parameters:
T
- the type of object the given consumers accept- Parameters:
consumers
- the consumers to evaluate- Returns:
- the
ThrowingConsumer
instance - Since:
- 3.25.0
-
doesNotHave
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.
- Since:
- 3.20.0
-
not
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.
- Since:
- 3.20.0
-
in
Create aFilterOperator
to 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.20.0
-
notIn
Create aFilterOperator
to 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.20.0
-
not
Create aFilterOperator
to 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.20.0
-
contentOf
Loads the text content of a file, so that it can be passed toAssertions.assertThat(String)
.Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
Assertions.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.- Since:
- 3.20.0
-
contentOf
Loads the text content of a file, so that it can be passed toAssertions.assertThat(String)
.Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
Assertions.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.- Since:
- 3.20.0
-
contentOf
Loads the text content of a file with the default character set, so that it can be passed toAssertions.assertThat(String)
.Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
Assertions.assertThat(File)
.- Parameters:
file
- the file.- Returns:
- the content of the file.
- Throws:
UncheckedIOException
- if an I/O exception occurs.- Since:
- 3.20.0
-
linesOf
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.- Since:
- 3.20.0
-
linesOf
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.- Since:
- 3.20.0
-
linesOf
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.- Since:
- 3.20.0
-
linesOf
Loads the text content of a file at a given path 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:
path
- the path.- Returns:
- the content of the file at the given path.
- Throws:
NullPointerException
- if the given charset isnull
.UncheckedIOException
- if an I/O exception occurs.- Since:
- 3.23.0
-
linesOf
Loads the text content of a file at a given path into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
path
- the path.charset
- the character set to use.- Returns:
- the content of the file at the given path.
- Throws:
NullPointerException
- if the given charset isnull
.UncheckedIOException
- if an I/O exception occurs.- Since:
- 3.23.0
-
linesOf
Loads the text content of a file at a given path into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
path
- the path.charsetName
- the name of the character set to use.- Returns:
- the content of the file at the given path.
- Throws:
NullPointerException
- if the given charset isnull
.UncheckedIOException
- if an I/O exception occurs.- Since:
- 3.23.0
-
contentOf
Loads the text content of a URL, so that it can be passed toAssertions.assertThat(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.20.0
-
contentOf
Loads the text content of a URL, so that it can be passed toAssertions.assertThat(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.20.0
-
contentOf
Loads the text content of a URL with the default character set, so that it can be passed toAssertions.assertThat(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.20.0
-
linesOf
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.20.0
-
linesOf
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.20.0
-
linesOf
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.20.0
-
setLenientDateParsing
public static 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 here
setLenientDateParsing(false)
.- Parameters:
value
- whether lenient parsing mode should be enabled or not- Since:
- 3.20.0
-
registerCustomDateFormat
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.SSSX, yyyy-MM-dd'T'HH:mm:ss.SSS, " + "yyyy-MM-dd'T'HH:mm:ssX, " + "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.- Since:
- 3.20.0
-
registerCustomDateFormat
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.SSSX, yyyy-MM-dd'T'HH:mm:ss.SSS, " + "yyyy-MM-dd'T'HH:mm:ssX, " + "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.- Since:
- 3.20.0
-
useDefaultDateFormatsOnly
public static 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 HH:mm:ss.SSSX
yyyy-MM-dd'T'HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss.SSS
(forTimestamp
String representation support)yyyy-MM-dd'T'HH:mm:ssX
yyyy-MM-dd'T'HH:mm:ss
yyyy-MM-dd
Example of valid string date representations:
2003-04-26T03:01:02.999
2003-04-26 03:01:02.999
2003-04-26T13:01:02
2003-04-26
- Since:
- 3.20.0
-
useRepresentation
Register aRepresentation
that will be used in all following assertions.Representation
are 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
- theRepresentation
to use- Since:
- 3.20.0
-
registerFormatterForType
Assertions error messages uses aRepresentation
to 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.5.0
-
useDefaultRepresentation
public static void useDefaultRepresentation()Fallback to useStandardRepresentation
to revert the effect of callinguseRepresentation(Representation)
.- Since:
- 3.20.0
-