public class BDDAssertions extends Assertions
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.| Modifier and Type | Field and Description |
|---|---|
static BDDAssertions |
and
A
BDDAssertions which allows to blend assertions with other libraries when the name 'then' cause clash. |
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| Modifier | Constructor and Description |
|---|---|
protected |
BDDAssertions()
Creates a new
. |
| Modifier and Type | Method and Description |
|---|---|
static <T> Condition<T> |
allOf(Condition<? super T>... conditions)
Creates a new
|
static <T> Condition<T> |
allOf(Iterable<? extends Condition<? super T>> conditions)
Creates a new
|
static <T> Condition<T> |
anyOf(Condition<? super T>... conditions)
Only delegate to
AnyOf.anyOf(Condition...) so that Assertions offers a full feature entry point to all
AssertJ features (but you can use AnyOf if you prefer). |
static <T> Condition<T> |
anyOf(Iterable<? extends Condition<? super T>> conditions)
Creates a new
|
static <T,ASSERT extends AbstractAssert<?,?>> |
as(InstanceOfAssertFactory<T,ASSERT> assertFactory)
A syntax sugar to write fluent assertion with methods having an
InstanceOfAssertFactory parameter. |
static Index |
atIndex(int index)
Only delegate to
Index.atIndex(int) so that Assertions offers a full feature entry point to all AssertJ
features (but you can use Index if you prefer). |
static Offset<BigDecimal> |
byLessThan(BigDecimal value)
Assertions entry point for BigDecimal
Offset to use with isCloseTo assertions. |
static Offset<BigInteger> |
byLessThan(BigInteger value)
Assertions entry point for BigInteger
Offset to use with isCloseTo assertions. |
static Offset<Byte> |
byLessThan(Byte value)
Assertions entry point for Byte
Offset to use with isCloseTo assertions. |
static Offset<Double> |
byLessThan(Double value)
Build a
strict Offset to use with AbstractDoubleAssert.isCloseTo(double, Offset) and AbstractDoubleAssert.isNotCloseTo(double, Offset) assertions. |
static Offset<Float> |
byLessThan(Float value)
Alias for
Assertions.offset(Float) to use with isCloseTo assertions. |
static Offset<Integer> |
byLessThan(Integer value)
|
static Offset<Long> |
byLessThan(Long value)
|
static TemporalUnitOffset |
byLessThan(long value,
TemporalUnit unit)
Assertions entry point for
TemporalUnitOffset with strict less than condition
to use with isCloseTo temporal assertions. |
static Offset<Short> |
byLessThan(Short value)
Assertions entry point for Short
Offset to use with isCloseTo assertions. |
static Exception |
catchException(ThrowableAssert.ThrowingCallable shouldRaiseException)
Allows catching an instance of
Exception. |
static IllegalArgumentException |
catchIllegalArgumentException(ThrowableAssert.ThrowingCallable shouldRaiseIllegalArgumentException)
Allows catching an instance of
IllegalArgumentException. |
static IllegalStateException |
catchIllegalStateException(ThrowableAssert.ThrowingCallable shouldRaiseIllegalStateException)
Allows catching an instance of
IllegalStateException. |
static IndexOutOfBoundsException |
catchIndexOutOfBoundsException(ThrowableAssert.ThrowingCallable shouldRaiseIndexOutOfBoundException)
Allows catching an instance of
IndexOutOfBoundsException. |
static IOException |
catchIOException(ThrowableAssert.ThrowingCallable shouldRaiseIOException)
Allows catching an instance of
IOException. |
static NullPointerException |
catchNullPointerException(ThrowableAssert.ThrowingCallable shouldRaiseNullPointerException)
Allows catching an instance of
NullPointerException. |
static ReflectiveOperationException |
catchReflectiveOperationException(ThrowableAssert.ThrowingCallable shouldRaiseReflectiveOperationException)
Allows catching an instance of
ReflectiveOperationException. |
static RuntimeException |
catchRuntimeException(ThrowableAssert.ThrowingCallable shouldRaiseRuntimeException)
Allows catching an instance of
RuntimeException. |
static Throwable |
catchThrowable(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Allows catching a
Throwable more easily when used with Java 8 lambdas. |
static <THROWABLE extends Throwable> |
catchThrowableOfType(ThrowableAssert.ThrowingCallable shouldRaiseThrowable,
Class<THROWABLE> type)
Allows catching a
Throwable of a specific type. |
static String |
contentOf(File file)
Loads the text content of a file with the default character set, so that it can be passed to
Assertions.assertThat(String). |
static String |
contentOf(File file,
Charset charset)
Loads the text content of a file, so that it can be passed to
Assertions.assertThat(String). |
static String |
contentOf(File file,
String charsetName)
Loads the text content of a file, so that it can be passed to
Assertions.assertThat(String). |
static String |
contentOf(URL url)
Loads the text content of a URL with the default character set, so that it can be passed to
Assertions.assertThat(String). |
static String |
contentOf(URL url,
Charset charset)
Loads the text content of a URL, so that it can be passed to
Assertions.assertThat(String). |
static String |
contentOf(URL url,
String charsetName)
Loads the text content of a URL, so that it can be passed to
Assertions.assertThat(String). |
static <T> DoesNotHave<T> |
doesNotHave(Condition<? super T> condition)
Creates a new
. |
static <K,V> MapEntry<K,V> |
entry(K key,
V value)
Only delegate to
MapEntry.entry(Object, Object) so that Assertions offers a full feature entry point to
all
AssertJ features (but you can use MapEntry if you prefer). |
static Properties<Object> |
extractProperty(String propertyName)
Only delegate to
Properties.extractProperty(String) so that Assertions offers a full feature entry point
to
all AssertJ features (but you can use Properties if you prefer). |
static <T> Properties<T> |
extractProperty(String propertyName,
Class<T> propertyType)
Only delegate to
Properties.extractProperty(String) so that Assertions offers a full feature entry point
to
all AssertJ features (but you can use Properties if you prefer). |
static <T> T |
fail(String failureMessage)
Throws an
AssertionError with the given message. |
static <T> T |
fail(String failureMessage,
Object... args)
Throws an
AssertionError with the given message built as String.format(String, Object...). |
static <T> T |
fail(String failureMessage,
Throwable realCause)
Throws an
AssertionError with the given message and with the Throwable that caused the failure. |
static <F,T> Function<F,T> |
from(Function<F,T> extractor)
A syntax sugar to write fluent assertion using
AbstractObjectAssert.returns(Object, Function) and
AbstractObjectAssert.doesNotReturn(Object, Function). |
static InFilter |
in(Object... values)
Create a
FilterOperator to use in filteredOn(String, FilterOperation) to express a filter keeping all Iterable elements whose property/field
value matches one of the given values. |
static List<String> |
linesOf(File file)
Loads the text content of a file into a list of strings with the default charset, each string corresponding to a
line.
|
static List<String> |
linesOf(File file,
Charset charset)
Loads the text content of a file into a list of strings, each string corresponding to a line.
|
static List<String> |
linesOf(File file,
String charsetName)
Loads the text content of a file into a list of strings, each string corresponding to a line.
|
static List<String> |
linesOf(Path path)
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.
|
static List<String> |
linesOf(Path path,
Charset charset)
Loads the text content of a file at a given path into a list of strings, each string corresponding to a line.
|
static List<String> |
linesOf(Path path,
String charsetName)
Loads the text content of a file at a given path into a list of strings, each string corresponding to a line.
|
static List<String> |
linesOf(URL url)
Loads the text content of a URL into a list of strings with the default charset, each string corresponding to a
line.
|
static List<String> |
linesOf(URL url,
Charset charset)
Loads the text content of a URL into a list of strings, each string corresponding to a line.
|
static List<String> |
linesOf(URL url,
String charsetName)
Loads the text content of a URL into a list of strings, each string corresponding to a line.
|
static <T> Not<T> |
not(Condition<? super T> condition)
Creates a new
. |
static NotFilter |
not(Object valueNotToMatch)
Create a
FilterOperator to use in filteredOn(String, FilterOperation) to express a filter keeping all Iterable elements whose property/field
value matches does not match the given value. |
static NotInFilter |
notIn(Object... valuesNotToMatch)
Create a
FilterOperator to use in filteredOn(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(DateFormat userCustomDateFormat)
Add the given date format to the ones used to parse date String in String based Date assertions like
AbstractDateAssert.isEqualTo(String). |
static void |
registerCustomDateFormat(String userCustomDateFormatPattern)
Add the given date format to the ones used to parse date String in String based Date assertions like
AbstractDateAssert.isEqualTo(String). |
static <T> void |
registerFormatterForType(Class<T> type,
Function<T,String> formatter)
Assertions error messages uses a
Representation 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
and
should be allowed to extract private fields, if not and they try it fails with exception. |
static void |
setDescriptionConsumer(Consumer<Description> descriptionConsumer)
All assertions description will be consumed by the given
Consumer<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 like
String 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 in
Throwable 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 an
AssertionError with a message explaining that a Throwable of given class was expected to be thrown
but had not been. |
static <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> |
then(ACTUAL actual,
Class<ELEMENT_ASSERT> assertClass)
Creates a new instance of
allowing to navigate to any Iterable element
in order to perform assertions on it. |
static <T> T |
then(AssertProvider<T> component)
Delegates the creation of the
Assert to the AssertProvider.assertThat() of the given component. |
static AtomicBooleanAssert |
then(AtomicBoolean actual)
Create assertion for
AtomicBoolean. |
static AtomicIntegerAssert |
then(AtomicInteger actual)
Create assertion for
AtomicInteger. |
static AtomicIntegerArrayAssert |
then(AtomicIntegerArray actual)
Create assertion for
AtomicIntegerArray. |
static <OBJECT> AtomicIntegerFieldUpdaterAssert<OBJECT> |
then(AtomicIntegerFieldUpdater<OBJECT> actual)
Create assertion for
AtomicIntegerFieldUpdater. |
static AtomicLongAssert |
then(AtomicLong actual)
Create assertion for
AtomicLong. |
static AtomicLongArrayAssert |
then(AtomicLongArray actual)
Create assertion for
AtomicLongArray. |
static <OBJECT> AtomicLongFieldUpdaterAssert<OBJECT> |
then(AtomicLongFieldUpdater<OBJECT> actual)
Create assertion for
AtomicLongFieldUpdater. |
static <VALUE> AtomicMarkableReferenceAssert<VALUE> |
then(AtomicMarkableReference<VALUE> actual)
Create assertion for
AtomicMarkableReference. |
static <VALUE> AtomicReferenceAssert<VALUE> |
then(AtomicReference<VALUE> actual)
Create assertion for
AtomicReference. |
static <ELEMENT> AtomicReferenceArrayAssert<ELEMENT> |
then(AtomicReferenceArray<ELEMENT> actual)
Create assertion for
AtomicReferenceArray. |
static <FIELD,OBJECT> |
then(AtomicReferenceFieldUpdater<OBJECT,FIELD> actual)
Create assertion for
AtomicReferenceFieldUpdater. |
static <VALUE> AtomicStampedReferenceAssert<VALUE> |
then(AtomicStampedReference<VALUE> actual)
Create assertion for
AtomicStampedReference. |
static AbstractBigDecimalAssert<?> |
then(BigDecimal actual)
Creates a new instance of
. |
static AbstractBigIntegerAssert<?> |
then(BigInteger actual)
Creates a new instance of
. |
static AbstractBooleanAssert<?> |
then(boolean actual)
Creates a new instance of
. |
static AbstractBooleanAssert<?> |
then(Boolean actual)
Creates a new instance of
. |
static AbstractBooleanArrayAssert<?> |
then(boolean[] actual)
Creates a new instance of
. |
static Boolean2DArrayAssert |
then(boolean[][] actual)
Creates a new instance of
. |
static AbstractByteAssert<?> |
then(byte actual)
Creates a new instance of
. |
static AbstractByteAssert<?> |
then(Byte actual)
Creates a new instance of
. |
static AbstractByteArrayAssert<?> |
then(byte[] actual)
Creates a new instance of
. |
static Byte2DArrayAssert |
then(byte[][] actual)
Creates a new instance of
. |
static AbstractCharacterAssert<?> |
then(char actual)
Creates a new instance of
. |
static AbstractCharArrayAssert<?> |
then(char[] actual)
Creates a new instance of
. |
static Char2DArrayAssert |
then(char[][] actual)
Creates a new instance of
. |
static AbstractCharacterAssert<?> |
then(Character actual)
Creates a new instance of
. |
static AbstractCharSequenceAssert<?,? extends CharSequence> |
then(CharSequence actual)
Creates a new instance of
. |
static ClassAssert |
then(Class<?> actual)
Creates a new instance of
|
static <E> AbstractCollectionAssert<?,Collection<? extends E>,E,ObjectAssert<E>> |
then(Collection<? extends E> actual)
Creates a new instance of
. |
static <RESULT> CompletableFutureAssert<RESULT> |
then(CompletableFuture<RESULT> future)
Create assertion for
CompletableFuture. |
static <RESULT> CompletableFutureAssert<RESULT> |
then(CompletionStage<RESULT> actual)
Create assertion for
CompletionStage by converting it to a CompletableFuture and returning a CompletableFutureAssert. |
static AbstractDateAssert<?> |
then(Date actual)
Creates a new instance of
. |
static AbstractDoubleAssert<?> |
then(double actual)
Creates a new instance of
. |
static AbstractDoubleAssert<?> |
then(Double actual)
Creates a new instance of
. |
static AbstractDoubleArrayAssert<?> |
then(double[] actual)
Creates a new instance of
. |
static Double2DArrayAssert |
then(double[][] actual)
Creates a new instance of
. |
static DoublePredicateAssert |
then(DoublePredicate actual)
Create assertion for
DoublePredicate. |
static ListAssert<Double> |
then(DoubleStream actual)
Creates a new instance of
from the given DoubleStream. |
static AbstractDurationAssert<?> |
then(Duration actual)
Creates a new instance of
. |
static AbstractFileAssert<?> |
then(File actual)
Creates a new instance of
. |
static AbstractFloatAssert<?> |
then(float actual)
Creates a new instance of
. |
static AbstractFloatAssert<?> |
then(Float actual)
Creates a new instance of
. |
static AbstractFloatArrayAssert<?> |
then(float[] actual)
Creates a new instance of
. |
static Float2DArrayAssert |
then(float[][] actual)
Creates a new instance of
. |
static <RESULT> FutureAssert<RESULT> |
then(Future<RESULT> actual)
Creates a new instance of
FutureAssert |
static AbstractInputStreamAssert<?,? extends InputStream> |
then(InputStream actual)
Creates a new instance of
. |
static AbstractInstantAssert<?> |
then(Instant actual)
Creates a new instance of
. |
static AbstractIntegerAssert<?> |
then(int actual)
Creates a new instance of
. |
static AbstractIntArrayAssert<?> |
then(int[] actual)
Creates a new instance of
. |
static Int2DArrayAssert |
then(int[][] actual)
Creates a new instance of
. |
static AbstractIntegerAssert<?> |
then(Integer actual)
Creates a new instance of
. |
static IntPredicateAssert |
then(IntPredicate actual)
Create assertion for
IntPredicate. |
static ListAssert<Integer> |
then(IntStream actual)
Creates a new instance of
from the given IntStream. |
static <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> |
then(Iterable<? extends ELEMENT> actual,
AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)
Creates a new instance of
allowing to navigate to any Iterable element
in order to perform assertions on it. |
static <T> IterableAssert<T> |
then(Iterable<? extends T> actual)
Creates a new instance of
. |
static <T> IteratorAssert<T> |
then(Iterator<? extends T> actual)
Creates a new instance of
. |
static <ACTUAL extends List<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> |
then(List<? extends ELEMENT> actual,
AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)
Creates a new instance of
allowing to navigate to any List element
in order to perform assertions on it. |
static <ELEMENT,ACTUAL extends List<? extends ELEMENT>,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> |
then(List<? extends ELEMENT> actual,
Class<ELEMENT_ASSERT> assertClass)
Creates a new instance of
allowing to navigate to any List element
in order to perform assertions on it. |
static <T> ListAssert<T> |
then(List<? extends T> actual)
Creates a new instance of
. |
static AbstractLocalDateAssert<?> |
then(LocalDate actual)
Creates a new instance of
. |
static AbstractLocalDateTimeAssert<?> |
then(LocalDateTime actual)
Creates a new instance of
. |
static AbstractLocalTimeAssert<?> |
then(LocalTime actual)
Creates a new instance of
. |
static AbstractLongAssert<?> |
then(long actual)
Creates a new instance of
. |
static AbstractLongAssert<?> |
then(Long actual)
Creates a new instance of
. |
static AbstractLongArrayAssert<?> |
then(long[] actual)
Creates a new instance of
. |
static Long2DArrayAssert |
then(long[][] actual)
Creates a new instance of
. |
static LongAdderAssert |
then(LongAdder actual)
Create assertion for
LongAdder. |
static LongPredicateAssert |
then(LongPredicate actual)
Create assertion for
LongPredicate. |
static ListAssert<Long> |
then(LongStream actual)
Creates a new instance of
from the given LongStream. |
static <K,V> MapAssert<K,V> |
then(Map<K,V> actual)
Creates a new instance of
. |
static MatcherAssert |
then(Matcher actual)
Create assertion for
Matcher |
static AbstractOffsetDateTimeAssert<?> |
then(OffsetDateTime actual)
Creates a new instance of
. |
static AbstractOffsetTimeAssert<?> |
then(OffsetTime actual)
Creates a new instance of
. |
static <VALUE> OptionalAssert<VALUE> |
then(Optional<VALUE> optional)
Create assertion for
Optional. |
static OptionalDoubleAssert |
then(OptionalDouble optional)
Create assertion for
OptionalDouble. |
static OptionalIntAssert |
then(OptionalInt optional)
Create assertion for
OptionalInt. |
static OptionalLongAssert |
then(OptionalLong optional)
Create assertion for
OptionalLong. |
static AbstractPathAssert<?> |
then(Path actual)
Creates a new instance of
PathAssert |
static AbstractPeriodAssert<?> |
then(Period actual)
Creates a new instance of
. |
static <T> PredicateAssert<T> |
then(Predicate<T> actual)
Create assertion for
Predicate. |
static AbstractShortAssert<?> |
then(short actual)
Creates a new instance of
. |
static AbstractShortAssert<?> |
then(Short actual)
Creates a new instance of
. |
static AbstractShortArrayAssert<?> |
then(short[] actual)
Creates a new instance of
. |
static Short2DArrayAssert |
then(short[][] actual)
Creates a new instance of
. |
static <ELEMENT> SpliteratorAssert<ELEMENT> |
then(Spliterator<ELEMENT> actual)
Creates a new instance of
from the given Spliterator. |
static <ELEMENT> ListAssert<ELEMENT> |
then(Stream<? extends ELEMENT> actual)
Creates a new instance of
from the given Stream. |
static AbstractStringAssert<?> |
then(String actual)
Creates a new instance of
. |
static AbstractCharSequenceAssert<?,? extends CharSequence> |
then(StringBuffer actual)
Creates a new instance of
from a StringBuffer. |
static AbstractCharSequenceAssert<?,? extends CharSequence> |
then(StringBuilder actual)
Creates a new instance of
from a StringBuilder. |
static <T> ObjectAssert<T> |
then(T actual)
Creates a new instance of
. |
static <T extends Comparable<? super T>> |
then(T actual)
Creates a new instance of
with
standard comparison semantics. |
static <T extends Throwable> |
then(T actual)
Creates a new instance of
. |
static <T extends AssertDelegateTarget> |
then(T assertion)
Returns the given assertion.
|
static <T> ObjectArrayAssert<T> |
then(T[] actual)
Creates a new instance of
. |
static <T> Object2DArrayAssert<T> |
then(T[][] actual)
Creates a new instance of
. |
static AbstractUriAssert<?> |
then(URI actual)
Creates a new instance of
. |
static AbstractUrlAssert<?> |
then(URL actual)
Creates a new instance of
. |
static AbstractZonedDateTimeAssert<?> |
then(ZonedDateTime actual)
Creates a new instance of
. |
static AbstractThrowableAssert<?,? extends Throwable> |
thenCode(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable)
Allows to capture and then assert on a
Throwable 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
. |
static <T> AbstractUniversalComparableAssert<?,T> |
thenComparable(Comparable<T> actual)
Creates a new instance of
with
standard comparison semantics. |
static ThrowableTypeAssert<Exception> |
thenException()
Alias for
thenExceptionOfType(Class) for Exception. |
static <T extends Throwable> |
thenExceptionOfType(Class<? extends T> exceptionType)
Entry point to check that an exception of type T is thrown by a given
throwingCallable
which allows to chain assertions on the thrown exception. |
static ThrowableTypeAssert<IllegalArgumentException> |
thenIllegalArgumentException()
Alias for
thenExceptionOfType(Class) for IllegalArgumentException. |
static ThrowableTypeAssert<IllegalStateException> |
thenIllegalStateException()
Alias for
thenExceptionOfType(Class) for IllegalStateException. |
static ThrowableTypeAssert<IndexOutOfBoundsException> |
thenIndexOutOfBoundsException()
Alias for
thenExceptionOfType(Class) for IndexOutOfBoundsException. |
static ThrowableTypeAssert<IOException> |
thenIOException()
Alias for
thenExceptionOfType(Class) for IOException. |
static <ELEMENT> IterableAssert<ELEMENT> |
thenIterable(Iterable<? extends ELEMENT> actual)
Creates a new instance of
. |
static <ELEMENT> IteratorAssert<ELEMENT> |
thenIterator(Iterator<? extends ELEMENT> actual)
Creates a new instance of
. |
static <ELEMENT> ListAssert<ELEMENT> |
thenList(List<? extends ELEMENT> actual)
Creates a new instance of
. |
static NotThrownAssert |
thenNoException()
Entry point to check that no exception of any type is thrown by a given
throwingCallable. |
static ThrowableTypeAssert<NullPointerException> |
thenNullPointerException()
Alias for
thenExceptionOfType(Class) for NullPointerException. |
static <T> ObjectAssert<T> |
thenObject(T actual)
Creates a new instance of
for any object. |
static AbstractPathAssert<?> |
thenPath(Path actual)
Creates a new instance of
PathAssert |
static <T> PredicateAssert<T> |
thenPredicate(Predicate<T> actual)
Create assertion for
Predicate. |
static ThrowableTypeAssert<ReflectiveOperationException> |
thenReflectiveOperationException()
Alias for
thenExceptionOfType(Class) for ReflectiveOperationException. |
static ThrowableTypeAssert<RuntimeException> |
thenRuntimeException()
Alias for
thenExceptionOfType(Class) for RuntimeException. |
static <ELEMENT> ListAssert<ELEMENT> |
thenStream(Stream<? extends ELEMENT> actual)
Creates a new instance of
from the given Stream. |
static AbstractThrowableAssert<?,? extends Throwable> |
thenThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Allows to capture and then assert on a
Throwable (easier done with lambdas). |
static AbstractThrowableAssert<?,? extends Throwable> |
thenThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable,
String description,
Object... args)
Allows to capture and then assert on a
Throwable like thenThrownBy(ThrowingCallable) but this method
let you set the assertion description the same way you do with as(String, Object...). |
static <T> ObjectAssert<T> |
thenWith(T actual,
Consumer<T>... requirements)
Uses the given instance as the instance under test for all the assertions expressed as the passed
Consumers. |
static Tuple |
tuple(Object... values)
Utility method to build nicely a
Tuple when working with AbstractIterableAssert.extracting(String...) or
AbstractObjectArrayAssert.extracting(String...) |
static void |
useDefaultDateFormatsOnly()
Remove all registered custom date formats => use only the defaults date formats to parse string as date.
|
static void |
useDefaultRepresentation()
Fallback to use
StandardRepresentation to revert the effect of calling useRepresentation(Representation). |
static void |
useRepresentation(Representation customRepresentation)
Register a
Representation that will be used in all following assertions. |
static Offset<BigDecimal> |
within(BigDecimal value)
Assertions entry point for BigDecimal
Offset to use with isCloseTo assertions. |
static Offset<BigInteger> |
within(BigInteger value)
Assertions entry point for BigInteger
Offset to use with isCloseTo assertions. |
static Offset<Byte> |
within(Byte value)
Assertions entry point for Byte
Offset to use with isCloseTo assertions. |
static Offset<Double> |
within(Double value)
Builds an
Offset to use with isCloseTo assertions. |
static Offset<Float> |
within(Float value)
Builds an
Offset to use with isCloseTo assertions. |
static Offset<Integer> |
within(Integer value)
Assertions entry point for Integer
Offset to use with isCloseTo assertions. |
static Offset<Long> |
within(Long value)
|
static TemporalUnitOffset |
within(long value,
TemporalUnit unit)
Assertions entry point for
TemporalUnitOffset with with less than or equal condition
to use with isCloseTo temporal assertions. |
static Offset<Short> |
within(Short value)
Assertions entry point for Short
Offset to use with isCloseTo assertions. |
static Percentage |
withinPercentage(Double value)
Assertions entry point for Double
Percentage to use with isCloseTo assertions for
percentages. |
static Percentage |
withinPercentage(Integer value)
Assertions entry point for Integer
Percentage to use with isCloseTo assertions for
percentages. |
static Percentage |
withinPercentage(Long value)
Assertions entry point for Long
Percentage to use with isCloseTo assertions for
percentages. |
static Duration |
withMarginOf(Duration allowedDifference)
Syntactic sugar method to use with
AbstractDurationAssert.isCloseTo(Duration, Duration) assertion. |
static Offset<Double> |
withPrecision(Double value)
Builds an
Offset to use with real number assertions. |
static Offset<Float> |
withPrecision(Float value)
Builds an
Offset to use with real number 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, assertThat, assertThat, assertThat, assertThatCode, assertThatCollection, assertThatComparable, assertThatException, assertThatExceptionOfType, assertThatIllegalArgumentException, assertThatIllegalStateException, assertThatIndexOutOfBoundsException, assertThatIOException, assertThatIterable, assertThatIterator, assertThatList, assertThatNoException, assertThatNullPointerException, assertThatObject, assertThatPath, assertThatPredicate, assertThatReflectiveOperationException, assertThatRuntimeException, assertThatStream, assertThatThrownBy, assertThatThrownBy, assertWith, failBecauseExceptionWasNotThrown, filter, filter, offset, offsetclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitarray, array2D, atomicIntegerFieldUpdater, atomicLongFieldUpdater, atomicMarkableReference, atomicReference, atomicReferenceArray, atomicReferenceFieldUpdater, atomicStampedReference, collection, comparable, completableFuture, completionStage, future, iterable, iterator, list, map, optional, predicate, spliterator, stream, throwable, typepublic static final BDDAssertions and
BDDAssertions 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();
}protected BDDAssertions()
BDDAssertions.public static <T> PredicateAssert<T> then(Predicate<T> actual)
Predicate.T - the type of the value contained in the Predicate.actual - the actual value.public static <T> PredicateAssert<T> thenPredicate(Predicate<T> actual)
Predicate.
Use this over then(Predicate) in case of ambiguous method resolution when the object under test
implements several interfaces Assertj provides then for.
T - the type of the value contained in the Predicate.actual - the actual value.public static IntPredicateAssert then(IntPredicate actual)
IntPredicate.actual - the actual value.public static LongPredicateAssert then(LongPredicate actual)
LongPredicate.actual - the actual value.public static DoublePredicateAssert then(DoublePredicate actual)
DoublePredicate.actual - the actual value.public static <VALUE> OptionalAssert<VALUE> then(Optional<VALUE> optional)
Optional.VALUE - the type of the value contained in the Optional.optional - the actual value.public static OptionalIntAssert then(OptionalInt optional)
OptionalInt.optional - the actual value.public static OptionalLongAssert then(OptionalLong optional)
OptionalLong.optional - the actual value.public static MatcherAssert then(Matcher actual)
Matcheractual - the actual matcherpublic static OptionalDoubleAssert then(OptionalDouble optional)
OptionalDouble.optional - the actual value.public static AbstractBigDecimalAssert<?> then(BigDecimal actual)
BigDecimalAssert.actual - the actual value.public static AbstractBigIntegerAssert<?> then(BigInteger actual)
BigIntegerAssert.actual - the actual value.public static AbstractBooleanAssert<?> then(boolean actual)
BooleanAssert.actual - the actual value.public static AbstractBooleanAssert<?> then(Boolean actual)
BooleanAssert.actual - the actual value.public static AbstractBooleanArrayAssert<?> then(boolean[] actual)
BooleanArrayAssert.actual - the actual value.public static Boolean2DArrayAssert then(boolean[][] actual)
Boolean2DArrayAssert.actual - the actual value.public static AbstractByteAssert<?> then(byte actual)
ByteAssert.actual - the actual value.public static AbstractByteAssert<?> then(Byte actual)
ByteAssert.actual - the actual value.public static AbstractByteArrayAssert<?> then(byte[] actual)
ByteArrayAssert.actual - the actual value.public static Byte2DArrayAssert then(byte[][] actual)
Byte2DArrayAssert.actual - the actual value.public static AbstractCharacterAssert<?> then(char actual)
CharacterAssert.actual - the actual value.public static AbstractCharArrayAssert<?> then(char[] actual)
CharArrayAssert.actual - the actual value.public static Char2DArrayAssert then(char[][] actual)
Char2DArrayAssert.actual - the actual value.public static AbstractCharacterAssert<?> then(Character actual)
CharacterAssert.actual - the actual value.public static ClassAssert then(Class<?> actual)
ClassAssertactual - the actual value.public static <T extends Comparable<? super T>> AbstractComparableAssert<?,T> then(T actual)
GenericComparableAssert with
standard comparison semantics.T - the actual typeactual - the actual value.public static <T> AbstractUniversalComparableAssert<?,T> thenComparable(Comparable<T> actual)
UniversalComparableAssert with
standard comparison semantics.
Use this over then(Comparable) in case of ambiguous method resolution when the object under test
implements several interfaces Assertj provides then for.
T - the type of actual.actual - the actual value.public static <T> IterableAssert<T> then(Iterable<? extends T> actual)
IterableAssert.T - the actual elements typeactual - the actual value.public static <ELEMENT> IterableAssert<ELEMENT> thenIterable(Iterable<? extends ELEMENT> actual)
IterableAssert.
Use this over then(Iterable) in case of ambiguous method resolution when the object under test
implements several interfaces Assertj provides then for.
ELEMENT - the type of elements.actual - the actual value.public static <T> IteratorAssert<T> then(Iterator<? extends T> actual)
IteratorAssert.
Breaking change in version 3.12.0: this method does not return anymore an IterableAssert but an IteratorAssert.
In order to access assertions from IterableAssert, use AbstractIteratorAssert.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 T - the actual elements typeactual - the actual value.public static <ELEMENT> IteratorAssert<ELEMENT> thenIterator(Iterator<? extends ELEMENT> actual)
IteratorAssert.
Use this over then(Iterator) in case of ambiguous method resolution when the object under test
implements several interfaces Assertj provides then for.
ELEMENT - the type of elements.actual - the actual value.public 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)
FactoryBasedNavigableIterableAssert allowing to navigate to any 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 given
AssertFactory<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");ACTUAL - The actual typeELEMENT - The actual elements typeELEMENT_ASSERT - The actual elements AbstractAssert typeactual - the actual value.assertFactory - the factory used to create the elements assert instance.public static <ACTUAL extends Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> ClassBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> then(ACTUAL actual, Class<ELEMENT_ASSERT> assertClass)
ClassBasedNavigableIterableAssert allowing to navigate to any 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");ACTUAL - The actual typeELEMENT - The actual elements typeELEMENT_ASSERT - The actual elements AbstractAssert typeactual - the actual value.assertClass - the class used to create the elements assert instance.public 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)
FactoryBasedNavigableListAssert allowing to navigate to any 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 given
AssertFactory<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");ACTUAL - The actual typeELEMENT - The actual elements typeELEMENT_ASSERT - The actual elements AbstractAssert typeactual - the actual value.assertFactory - the factory used to create the elements assert instance.public static <ELEMENT,ACTUAL extends List<? extends ELEMENT>,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> ClassBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> then(List<? extends ELEMENT> actual, Class<ELEMENT_ASSERT> assertClass)
ClassBasedNavigableListAssert allowing to navigate to any 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");ACTUAL - The actual typeELEMENT - The actual elements typeELEMENT_ASSERT - The actual elements AbstractAssert typeactual - the actual value.assertClass - the class used to create the elements assert instance.public static AbstractDoubleAssert<?> then(double actual)
DoubleAssert.actual - the actual value.public static AbstractDoubleAssert<?> then(Double actual)
DoubleAssert.actual - the actual value.public static AbstractDoubleArrayAssert<?> then(double[] actual)
DoubleArrayAssert.actual - the actual value.public static Double2DArrayAssert then(double[][] actual)
Double2DArrayAssert.actual - the actual value.public static AbstractFileAssert<?> then(File actual)
FileAssert.actual - the actual value.public static AbstractPathAssert<?> then(Path actual)
PathAssertactual - the path to testpublic static AbstractPathAssert<?> thenPath(Path actual)
PathAssert
Use this over then(Path) in case of ambiguous method resolution when the object under test
implements several interfaces Assertj provides then for.
actual - the path to testpublic static <RESULT> FutureAssert<RESULT> then(Future<RESULT> actual)
FutureAssertRESULT - the type of the value contained in the Future.actual - the future to testpublic static AbstractInputStreamAssert<?,? extends InputStream> then(InputStream actual)
InputStreamAssert.actual - the actual value.public static AbstractFloatAssert<?> then(float actual)
FloatAssert.actual - the actual value.public static AbstractFloatAssert<?> then(Float actual)
FloatAssert.actual - the actual value.public static AbstractFloatArrayAssert<?> then(float[] actual)
FloatArrayAssert.actual - the actual value.public static Float2DArrayAssert then(float[][] actual)
Float2DArrayAssert.actual - the actual value.public static AbstractIntegerAssert<?> then(int actual)
IntegerAssert.actual - the actual value.public static AbstractIntArrayAssert<?> then(int[] actual)
IntArrayAssert.actual - the actual value.public static Int2DArrayAssert then(int[][] actual)
Int2DArrayAssert.actual - the actual value.public static AbstractIntegerAssert<?> then(Integer actual)
IntegerAssert.actual - the actual value.public static <E> AbstractCollectionAssert<?,Collection<? extends E>,E,ObjectAssert<E>> then(Collection<? extends E> actual)
CollectionAssert.E - the type of elements.actual - the actual value.public static <E> AbstractCollectionAssert<?,Collection<? extends E>,E,ObjectAssert<E>> thenCollection(Collection<? extends E> actual)
CollectionAssert.
Use this over then(Collection) in case of ambiguous method resolution when the object under test
implements several interfaces Assertj provides then for.
E - the type of elements.actual - the actual value.public static <T> ListAssert<T> then(List<? extends T> actual)
ListAssert.T - the type of elements.actual - the actual value.public static <ELEMENT> ListAssert<ELEMENT> thenList(List<? extends ELEMENT> actual)
ListAssert.
Use this over then(List) in case of ambiguous method resolution when the object under test
implements several interfaces Assertj provides then for.
ELEMENT - the type of elements.actual - the actual value.public static AbstractLongAssert<?> then(long actual)
LongAssert.actual - the actual value.public static AbstractLongAssert<?> then(Long actual)
LongAssert.actual - the actual value.public static AbstractLongArrayAssert<?> then(long[] actual)
LongArrayAssert.actual - the actual value.public static Long2DArrayAssert then(long[][] actual)
Long2DArrayAssert.actual - the actual value.public static <T> ObjectAssert<T> then(T actual)
ObjectAssert.T - the type of the actual value.actual - the actual value.public static <T> ObjectArrayAssert<T> then(T[] actual)
ObjectArrayAssert.T - the actual's elements type.actual - the actual value.public static <T> Object2DArrayAssert<T> then(T[][] actual)
Object2DArrayAssert.T - the actual's elements type.actual - the actual value.public static <K,V> MapAssert<K,V> then(Map<K,V> actual)
MapAssert.K - the type of keys in the map.V - the type of values in the map.actual - the actual value.public static AbstractShortAssert<?> then(short actual)
ShortAssert.actual - the actual value.public static AbstractShortAssert<?> then(Short actual)
ShortAssert.actual - the actual value.public static AbstractShortArrayAssert<?> then(short[] actual)
ShortArrayAssert.actual - the actual value.public static Short2DArrayAssert then(short[][] actual)
Short2DArrayAssert.actual - the actual value.public static AbstractCharSequenceAssert<?,? extends CharSequence> then(CharSequence actual)
CharSequenceAssert.actual - the actual value.public static AbstractCharSequenceAssert<?,? extends CharSequence> then(StringBuilder actual)
CharSequenceAssert from a StringBuilder.actual - the actual value.public static AbstractCharSequenceAssert<?,? extends CharSequence> then(StringBuffer actual)
CharSequenceAssert from a StringBuffer.actual - the actual value.public static AbstractStringAssert<?> then(String actual)
StringAssert.actual - the actual value.public static AbstractDateAssert<?> then(Date actual)
DateAssert.actual - the actual value.public static AtomicBooleanAssert then(AtomicBoolean actual)
AtomicBoolean.actual - the actual value.public static AtomicIntegerAssert then(AtomicInteger actual)
AtomicInteger.actual - the actual value.public static AtomicIntegerArrayAssert then(AtomicIntegerArray actual)
AtomicIntegerArray.actual - the actual value.public static <OBJECT> AtomicIntegerFieldUpdaterAssert<OBJECT> then(AtomicIntegerFieldUpdater<OBJECT> actual)
AtomicIntegerFieldUpdater.OBJECT - the type of the object holding the updatable field.actual - the actual value.public static LongAdderAssert then(LongAdder actual)
LongAdder.actual - the actual value.public static AtomicLongAssert then(AtomicLong actual)
AtomicLong.actual - the actual value.public static AtomicLongArrayAssert then(AtomicLongArray actual)
AtomicLongArray.actual - the actual value.public static <OBJECT> AtomicLongFieldUpdaterAssert<OBJECT> then(AtomicLongFieldUpdater<OBJECT> actual)
AtomicLongFieldUpdater.OBJECT - the type of the object holding the updatable field.actual - the actual value.public static <VALUE> AtomicReferenceAssert<VALUE> then(AtomicReference<VALUE> actual)
AtomicReference.VALUE - the type of the value contained in the AtomicReference.actual - the actual value.public static <ELEMENT> AtomicReferenceArrayAssert<ELEMENT> then(AtomicReferenceArray<ELEMENT> actual)
AtomicReferenceArray.ELEMENT - the type of the value contained in the AtomicReferenceArray.actual - the actual value.public static <FIELD,OBJECT> AtomicReferenceFieldUpdaterAssert<FIELD,OBJECT> then(AtomicReferenceFieldUpdater<OBJECT,FIELD> actual)
AtomicReferenceFieldUpdater.FIELD - the type of the field which gets updated by the AtomicReferenceFieldUpdater.OBJECT - the type of the object holding the updatable field.actual - the actual value.public static <VALUE> AtomicMarkableReferenceAssert<VALUE> then(AtomicMarkableReference<VALUE> actual)
AtomicMarkableReference.VALUE - the type of the value contained in the AtomicMarkableReference.actual - the actual value.public static <VALUE> AtomicStampedReferenceAssert<VALUE> then(AtomicStampedReference<VALUE> actual)
AtomicStampedReference.VALUE - the type of the value contained in the AtomicStampedReference.actual - the actual value.public static <T extends Throwable> AbstractThrowableAssert<?,T> then(T actual)
ThrowableAssert.T - the type of the actual throwable.actual - the actual value.public static AbstractThrowableAssert<?,? extends Throwable> thenThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Throwable (easier done with lambdas).
Example :
@Test
public void testException() {
thenThrownBy(() -> { throw new Exception("boom!") }).isInstanceOf(Exception.class)
.hasMessageContaining("boom");
}
If the provided ThrowableAssert.ThrowingCallable does not raise an exception, an error is immediately thrown,
in that case the test description provided with as(String, Object...) is not honored.#catchThrowable(ThrowingCallable) as shown below:
// 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);
Alternatively you can also use assertThatCode(ThrowingCallable) for the test description provided
with as(String, Object...) to always be honored.shouldRaiseThrowable - The ThrowableAssert.ThrowingCallable or lambda with the code that should raise the throwable.ThrowableAssert.public static AbstractThrowableAssert<?,? extends Throwable> thenThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, String description, Object... args)
Throwable like thenThrownBy(ThrowingCallable) but this method
let you set the assertion description the same way you do with as(String, Object...).
Example:
@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");
}
If the provided 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);shouldRaiseThrowable - The ThrowableAssert.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.ThrowableAssert.public static AbstractThrowableAssert<?,? extends Throwable> thenCode(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable)
Throwable more easily when used with Java 8 lambdas.
Example :
ThrowingCallable callable = () -> {
throw new Exception("boom!");
};
// assertion succeeds
thenCode(callable).isInstanceOf(Exception.class)
.hasMessageContaining("boom");
// assertion fails
thenCode(callable).doesNotThrowAnyException();
If the provided ThrowableAssert.ThrowingCallable does not validate against next assertions, an error is immediately raised,
in that case the test description provided with as(String, Object...) is not honored.#catchThrowable(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 :(
shouldRaiseOrNotThrowable - The ThrowableAssert.ThrowingCallable or lambda with the code that should raise the throwable.null if none was raised by the callable.public static <T> ObjectAssert<T> thenObject(T actual)
ObjectAssert for any object.
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:
then(new LinkedList<>(asList("abc"))).matches(list -> ((Deque<String>) list).getFirst().equals("abc"));
No cast needed, but also no additional list assertions:
thenObject(new LinkedList<>(asList("abc"))).matches(list -> list.getFirst().equals("abc")); T - the type of the actual value.actual - the actual value.@SafeVarargs public static <T> ObjectAssert<T> thenWith(T actual, Consumer<T>... requirements)
Consumers.
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 of AbstractAssert.satisfies(Consumer[]) hopefully easier to find for some users.
T - the type of the actual value.actual - the actual value.requirements - to assert on the actual object - must not be null.public static AbstractLocalDateAssert<?> then(LocalDate actual)
LocalDateAssert.actual - the actual value.public static AbstractLocalDateTimeAssert<?> then(LocalDateTime actual)
LocalDateTimeAssert.actual - the actual value.public static AbstractZonedDateTimeAssert<?> then(ZonedDateTime actual)
ZonedDateTimeAssert.actual - the actual value.public static AbstractLocalTimeAssert<?> then(LocalTime actual)
LocalTimeAssert.actual - the actual value.public static AbstractOffsetTimeAssert<?> then(OffsetTime actual)
OffsetTimeAssert.actual - the actual value.public static AbstractInstantAssert<?> then(Instant actual)
InstantAssert.actual - the actual value.public static AbstractDurationAssert<?> then(Duration actual)
DurationAssert.actual - the actual value.public static AbstractPeriodAssert<?> then(Period actual)
PeriodAssert.actual - the actual value.public static AbstractUriAssert<?> then(URI actual)
UriAssert.actual - the actual value.public static AbstractUrlAssert<?> then(URL actual)
UrlAssert.actual - the actual value.public static AbstractOffsetDateTimeAssert<?> then(OffsetDateTime actual)
OffsetTimeAssert.actual - the actual value.public static <RESULT> CompletableFutureAssert<RESULT> then(CompletableFuture<RESULT> future)
CompletableFuture.RESULT - the type of the value contained in the CompletableFuture.future - the actual value.public static <RESULT> CompletableFutureAssert<RESULT> then(CompletionStage<RESULT> actual)
CompletionStage by converting it to a CompletableFuture and returning a CompletableFutureAssert.
If the given CompletionStage is null, the CompletableFuture in the returned CompletableFutureAssert will also be null.
RESULT - the type of the value contained in the CompletionStage.actual - the actual value.public static <T extends AssertDelegateTarget> T then(T assertion)
then.
Consider for example the following MyButton and MyButtonAssert classes:
public 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();
}
}
As MyButtonAssert implements AssertDelegateTarget, you can use then(buttonAssert).isBlinking();
instead of buttonAssert.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();
}T - the generic type of the user-defined assert.assertion - the assertion to return.public static <T> T then(AssertProvider<T> component)
Assert to the AssertProvider.assertThat() of the given component.
Read the comments on AssertProvider for an example of its usage.
T - the AssertProvider wrapped type.component - the component that creates its own assertAssert of the given componentpublic static <ELEMENT> ListAssert<ELEMENT> then(Stream<? extends ELEMENT> actual)
ListAssert from the given Stream.
Be aware that the Stream under test will be converted to a List when an assertions require to inspect its content.
Once this is done the Stream can't reused as it would have been consumed.
Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the Stream.
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 and isSameAs 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);ELEMENT - the type of elements.actual - the actual Stream value.public static <ELEMENT> ListAssert<ELEMENT> thenStream(Stream<? extends ELEMENT> actual)
ListAssert from the given Stream.
Use this over then(Stream) in case of ambiguous method resolution when the object under test
implements several interfaces Assertj provides then for.
Be aware that the Stream under test will be converted to a List when an assertions require to inspect its content.
Once this is done the Stream can't reused as it would have been consumed.
Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the Stream.
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 and isSameAs 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);ELEMENT - the type of elements.actual - the actual value.public static ListAssert<Double> then(DoubleStream actual)
ListAssert from the given DoubleStream.
Be aware that the DoubleStream under test will be converted to a List when an assertions require to inspect its content.
Once this is done the DoubleStream can't reused as it would have been consumed.
Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the DoubleStream.
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 and isSameAs 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);actual - the actual DoubleStream value.public static ListAssert<Long> then(LongStream actual)
ListAssert from the given LongStream.
Be aware that the LongStream under test will be converted to a List when an assertions require to inspect its content.
Once this is done the LongStream can't reused as it would have been consumed.
Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the LongStream.
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 and isSameAs 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);actual - the actual LongStream value.public static ListAssert<Integer> then(IntStream actual)
ListAssert from the given IntStream.
Be aware that the IntStream under test will be converted to a List when an assertions require to inspect its content.
Once this is done the IntStream can't reused as it would have been consumed.
Calling multiple methods on the returned ListAssert is safe as it only interacts with the List built from the IntStream.
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 and isSameAs 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);actual - the actual IntStream value.public static <ELEMENT> SpliteratorAssert<ELEMENT> then(Spliterator<ELEMENT> actual)
SpliteratorAssert from the given Spliterator.
Example:
Spliterator<Integer> spliterator = Stream.of(1, 2, 3).spliterator();
then(spliterator).hasCharacteristics(Spliterator.SIZED); ELEMENT - the type of elements.actual - the spliterator to test.public static Throwable catchThrowable(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Throwable 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");
} shouldRaiseThrowable - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowableOfType(ThrowingCallable, Class)public static <THROWABLE extends Throwable> THROWABLE catchThrowableOfType(ThrowableAssert.ThrowingCallable shouldRaiseThrowable, Class<THROWABLE> type)
Throwable of a specific type.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable 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);THROWABLE - the Throwable type.shouldRaiseThrowable - The lambda with the code that should raise the exception.type - The type of exception that the code is expected to raise.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static Exception catchException(ThrowableAssert.ThrowingCallable shouldRaiseException)
Exception.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable is of type Exception 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!");});shouldRaiseException - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static RuntimeException catchRuntimeException(ThrowableAssert.ThrowingCallable shouldRaiseRuntimeException)
RuntimeException.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable is of type RuntimeException 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!");});shouldRaiseRuntimeException - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static NullPointerException catchNullPointerException(ThrowableAssert.ThrowingCallable shouldRaiseNullPointerException)
NullPointerException.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable is of type RuntimeException 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!");});shouldRaiseNullPointerException - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static IllegalArgumentException catchIllegalArgumentException(ThrowableAssert.ThrowingCallable shouldRaiseIllegalArgumentException)
IllegalArgumentException.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable is of type IllegalArgumentException and casts it making it convenient to perform subtype-specific assertions on it.
Example:
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();
// fails as the thrown instance is not an IllegalArgumentException
catchIllegalArgumentException(() -> {throw new Exception("boom!");});shouldRaiseIllegalArgumentException - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static IOException catchIOException(ThrowableAssert.ThrowingCallable shouldRaiseIOException)
IOException.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable is of type IOException 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!");});shouldRaiseIOException - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static ReflectiveOperationException catchReflectiveOperationException(ThrowableAssert.ThrowingCallable shouldRaiseReflectiveOperationException)
ReflectiveOperationException.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable is of type ReflectiveOperationException 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!");});shouldRaiseReflectiveOperationException - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static IllegalStateException catchIllegalStateException(ThrowableAssert.ThrowingCallable shouldRaiseIllegalStateException)
IllegalStateException.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable is of type IllegalStateException 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!");});shouldRaiseIllegalStateException - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static IndexOutOfBoundsException catchIndexOutOfBoundsException(ThrowableAssert.ThrowingCallable shouldRaiseIndexOutOfBoundException)
IndexOutOfBoundsException.
A call is made to catchThrowable(ThrowingCallable), if no exception is thrown it returns null
otherwise it checks that the caught Throwable is of type IndexOutOfBoundsException 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!");});shouldRaiseIndexOutOfBoundException - The lambda with the code that should raise the exception.null if none was raised by the callable.#catchThrowable(ThrowingCallable)public static <T extends Throwable> ThrowableTypeAssert<T> thenExceptionOfType(Class<? extends T> exceptionType)
throwingCallable
which allows to chain assertions on the thrown exception.
Example:
thenExceptionOfType(IOException.class)
.isThrownBy(() -> { throw new IOException("boom!"); })
.withMessage("boom!");
This method is more or less the same of #thenThrownBy(ThrowingCallable) but in a more natural way.T - the exception type.exceptionType - the exception type class.ThrowableTypeAssert.public static NotThrownAssert thenNoException()
throwingCallable.
Example:
thenNoException().isThrownBy(() -> { System.out.println("OK"); });
This method is more or less the same of thenCode(...).doesNotThrowAnyException(); but in a more natural way.NotThrownAssert.public static ThrowableTypeAssert<NullPointerException> thenNullPointerException()
thenExceptionOfType(Class) for NullPointerException.ThrowableTypeAssert.public static ThrowableTypeAssert<IllegalArgumentException> thenIllegalArgumentException()
thenExceptionOfType(Class) for IllegalArgumentException.ThrowableTypeAssert.public static ThrowableTypeAssert<IOException> thenIOException()
thenExceptionOfType(Class) for IOException.ThrowableTypeAssert.public static ThrowableTypeAssert<IllegalStateException> thenIllegalStateException()
thenExceptionOfType(Class) for IllegalStateException.ThrowableTypeAssert.public static ThrowableTypeAssert<Exception> thenException()
thenExceptionOfType(Class) for Exception.ThrowableTypeAssert.public static ThrowableTypeAssert<IndexOutOfBoundsException> thenIndexOutOfBoundsException()
thenExceptionOfType(Class) for IndexOutOfBoundsException.ThrowableTypeAssert.public static ThrowableTypeAssert<ReflectiveOperationException> thenReflectiveOperationException()
thenExceptionOfType(Class) for ReflectiveOperationException.ThrowableTypeAssert.public static ThrowableTypeAssert<RuntimeException> thenRuntimeException()
thenExceptionOfType(Class) for RuntimeException.ThrowableTypeAssert.public static void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace)
Default is true.
removeAssertJRelatedElementsFromStackTrace - flag.public static <T> T fail(String failureMessage)
AssertionError with the given message.T - dummy return value typefailureMessage - error message.doSomething(optional.orElseGet(() -> fail("boom")));.AssertionError - with the given message.public static <T> T fail(String failureMessage, Object... args)
AssertionError with the given message built as String.format(String, Object...).T - dummy return value typefailureMessage - error message.args - Arguments referenced by the format specifiers in the format string.doSomething(optional.orElseGet(() -> fail("b%s", ""oom)));.AssertionError - with the given built message.public static <T> T fail(String failureMessage, Throwable realCause)
AssertionError with the given message and with the Throwable that caused the failure.T - dummy return value typefailureMessage - the description of the failed assertion. It can be null.realCause - cause of the error.doSomething(optional.orElseGet(() -> fail("boom", cause)));.AssertionError - with the given message and with the Throwable that caused the failure.public static <T> T shouldHaveThrown(Class<? extends Throwable> throwableClass)
AssertionError with a message explaining that a Throwable of given class was expected to be thrown
but had not been.T - dummy return value typethrowableClass - the Throwable class that was expected to be thrown.doSomething(optional.orElseGet(() -> shouldHaveThrown(IOException.class)));.AssertionError - with a message explaining that a Throwable of given class was expected to be thrown but had
not been.public static void setMaxLengthForSingleLineDescription(int maxLengthForSingleLineDescription)
The default value for maxLengthForSingleLineDescription is .
The following array will be formatted on one line as its length <= 80:
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"]
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", "Guards! Guards! (Discworld)");
// formatted as:
["A Game of Thrones",
"The Lord of the Rings",
"Assassin's Apprentice",
"Guards! Guards! (Discworld)"]maxLengthForSingleLineDescription - the maximum length for an iterable/array to be displayed on one linepublic static void setMaxElementsForPrinting(int maxElementsForPrinting)
Example with a value of 4.
The following array will be formatted entirely as it's length is <= 4:
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"]
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", "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"]maxElementsForPrinting - the maximum elements that would be printed for iterables, arrays and maps.public static void setPrintAssertionsDescription(boolean printAssertionsDescription)
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 with setDescriptionConsumer(Consumer).
printAssertionsDescription - whether to print assertions description.public static void setDescriptionConsumer(Consumer<Description> descriptionConsumer)
Consumer<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);
descriptionConsumer - the Description consumerpublic static void setMaxStackTraceElementsDisplayed(int maxStackTraceElementsDisplayed)
Throwable 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)maxStackTraceElementsDisplayed - the maximum number of lines for a stacktrace to be displayed on one throw.Configurationpublic static <T> Properties<T> extractProperty(String propertyName, Class<T> propertyType)
Properties.extractProperty(String) so that Assertions offers a full feature entry point
to
all AssertJ features (but you can use Properties if you prefer).
Typical usage is to chain extractProperty with from 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");T - the type of value to extract.propertyName - the name of the property to be read from the elements of a Iterable. It may be a nested
property (e.g. "address.street.number").propertyType - the type of property to extractProperties.NullPointerException - if the given property name is null.IllegalArgumentException - if the given property name is empty.public static Properties<Object> extractProperty(String propertyName)
Properties.extractProperty(String) so that Assertions offers a full feature entry point
to
all AssertJ features (but you can use Properties if you prefer).
Typical usage is to chain extractProperty with from 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"); propertyName - the name of the property to be read from the elements of a Iterable. It may be a nested
property (e.g. "address.street.number").Properties.NullPointerException - if the given property name is null.IllegalArgumentException - if the given property name is empty.public static Tuple tuple(Object... values)
Tuple when working with AbstractIterableAssert.extracting(String...) or
AbstractObjectArrayAssert.extracting(String...)public static void setAllowExtractingPrivateFields(boolean allowExtractingPrivateFields)
IterableAssert#extracting(String)
and
ObjectArrayAssert#extracting(String)
should be allowed to extract private fields, if not and they try it fails with exception.allowExtractingPrivateFields - allow private fields extraction. Default is true.public static void setAllowComparingPrivateFields(boolean allowComparingPrivateFields)
AbstractIterableAssert.usingElementComparatorOnFields(java.lang.String...)
AbstractObjectAssert.isEqualToComparingFieldByField(Object)false and these methods try to compare private fields, it will fail with an exception.allowComparingPrivateFields - allow private fields comparison. Default is true.public static void setExtractBareNamePropertyMethods(boolean barenamePropertyMethods)
String name().
Defaults to enabled.barenamePropertyMethods - whether bare-named property methods are foundpublic static <K,V> MapEntry<K,V> entry(K key, V value)
MapEntry.entry(Object, Object) so that Assertions offers a full feature entry point to
all
AssertJ features (but you can use MapEntry if you prefer).
Typical usage is to call entry in MapAssert contains assertion, see examples below :
Map<Ring, TolkienCharacter> ringBearers = ... // init omitted
assertThat(ringBearers).contains(entry(oneRing, frodo), entry(nenya, galadriel));K - the type of keys in the map.V - the type of values in the map.key - the key of the entry to create.value - the value of the entry to create.MapEntry.public static Index atIndex(int index)
Index.atIndex(int) so that Assertions offers a full feature entry point to all AssertJ
features (but you can use Index 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));index - the value of the index.Index.IllegalArgumentException - if the given value is negative.public static Offset<Double> within(Double value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(0.1).isCloseTo(0.0, within(0.1));value - the allowed offsetOffset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Double> withPrecision(Double value)
Offset to use with real number assertions.
Typical usage :
assertThat(0.1).isEqualTo(0.0, withPrecision(0.1));value - the required precisionOffset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Float> within(Float value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(8.2f).isCloseTo(8.0f, within(0.2f));value - the allowed offsetOffset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Float> withPrecision(Float value)
Offset to use with real number assertions.
Typical usage :
assertThat(0.2f).isEqualTo(0.0f, withPrecision(0.2f));value - the required precisionOffset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<BigDecimal> within(BigDecimal value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), within(BigDecimal.ONE));value - the allowed offsetOffset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<BigInteger> within(BigInteger value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), within(new BigInteger("2")));value - the allowed offsetOffset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Byte> within(Byte value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat((byte) 10).isCloseTo((byte) 11, within((byte) 1));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Integer> within(Integer value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(10).isCloseTo(11, within(1));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Short> within(Short value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(10).isCloseTo(11, within(1));value - the allowed offsetOffset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Long> within(Long value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(5l).isCloseTo(7l, within(2l));value - the allowed offsetOffset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static TemporalUnitOffset within(long value, TemporalUnit unit)
TemporalUnitOffset with 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));value - the allowed offsetunit - the TemporalUnit of the offsetOffset.public static Duration withMarginOf(Duration allowedDifference)
AbstractDurationAssert.isCloseTo(Duration, Duration) assertion.
Example:
assertThat(Duration.ofMinutes(2)).isCloseTo(Duration.ofMinutes(3), withMarginOf(Duration.ofMinutes(1)));allowedDifference - the allowed difference Duration.public static Percentage withinPercentage(Double value)
Percentage to use with isCloseTo assertions for
percentages.
Typical usage :
assertThat(11.0).isCloseTo(10.0, withinPercentage(10.0));value - the required precision percentagePercentage.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Percentage withinPercentage(Integer value)
Percentage to use with isCloseTo assertions for
percentages.
Typical usage :
assertThat(11).isCloseTo(10, withinPercentage(10));value - the required precision percentagePercentage.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Percentage withinPercentage(Long value)
Percentage to use with isCloseTo assertions for
percentages.
Typical usage :
assertThat(11L).isCloseTo(10L, withinPercentage(10L));value - the required precision percentagePercentage.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Double> byLessThan(Double value)
strict Offset to use with AbstractDoubleAssert.isCloseTo(double, Offset) and AbstractDoubleAssert.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));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Float> byLessThan(Float value)
Assertions.offset(Float) to use with isCloseTo assertions.
Typical usage :
assertThat(8.2f).isCloseTo(8.0f, byLessThan(0.5f));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<BigDecimal> byLessThan(BigDecimal value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), byLessThan(BigDecimal.ONE));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<BigInteger> byLessThan(BigInteger value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), byLessThan(new BigInteger("2")));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Byte> byLessThan(Byte value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat((byte) 10).isCloseTo((byte) 11, byLessThan((byte) 2));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Integer> byLessThan(Integer value)
Offset to use with strict isCloseTo assertions.
Typical usage :
assertThat(10).isCloseTo(12, byLessThan(1));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Short> byLessThan(Short value)
Offset to use with isCloseTo assertions.
Typical usage :
assertThat((short) 10).isCloseTo((short) 11, byLessThan((short) 2));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static Offset<Long> byLessThan(Long value)
Offset to use with strict isCloseTo assertions.
Typical usage :
assertThat(5l).isCloseTo(7l, byLessThan(3l));value - the value of the offset.Offset.NullPointerException - if the given value is null.IllegalArgumentException - if the given value is negative.public static TemporalUnitOffset byLessThan(long value, TemporalUnit unit)
TemporalUnitOffset with strict less than 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, byLessThan(5, ChronoUnit.MINUTES));value - the value of the offset.unit - the TemporalUnit of the offset.Offset.public static <F,T> Function<F,T> from(Function<F,T> extractor)
AbstractObjectAssert.returns(Object, Function) and
AbstractObjectAssert.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)); F - Type of test subjectT - Type of the property under the assertionextractor - A function to extract test subject's propertyextractorpublic static <T,ASSERT extends AbstractAssert<?,?>> InstanceOfAssertFactory<T,ASSERT> as(InstanceOfAssertFactory<T,ASSERT> assertFactory)
InstanceOfAssertFactory parameter.
Example:
Jedi yoda = new Jedi("Yoda", "Green");
assertThat(yoda).extracting(Jedi::getName, as(InstanceOfAssertFactories.STRING))
.startsWith("Yo");T - the type to use for the cast.ASSERT - the type of the resulting AssertassertFactory - the factory which verifies the type and creates the new AssertassertFactoryAbstractObjectAssert.extracting(String, InstanceOfAssertFactory),
AbstractObjectAssert.extracting(Function, InstanceOfAssertFactory),
AbstractMapAssert.extractingByKey(Object, InstanceOfAssertFactory),
AbstractOptionalAssert.get(InstanceOfAssertFactory),
AbstractIterableAssert.first(InstanceOfAssertFactory),
AbstractIterableAssert.last(InstanceOfAssertFactory),
AbstractIterableAssert.element(int, InstanceOfAssertFactory)@SafeVarargs public static <T> Condition<T> allOf(Condition<? super T>... conditions)
AllOfT - the type of object the given condition accept.conditions - the conditions to evaluate.AllOf.NullPointerException - if the given array is null.NullPointerException - if any of the elements in the given array is null.public static <T> Condition<T> allOf(Iterable<? extends Condition<? super T>> conditions)
AllOfT - the type of object the given condition accept.conditions - the conditions to evaluate.AllOf.NullPointerException - if the given iterable is null.NullPointerException - if any of the elements in the given iterable is null.@SafeVarargs public static <T> Condition<T> anyOf(Condition<? super T>... conditions)
AnyOf.anyOf(Condition...) so that Assertions offers a full feature entry point to all
AssertJ features (but you can use AnyOf if you prefer).
Typical usage (jedi and sith are Condition) :
assertThat("Vader").is(anyOf(jedi, sith));T - the type of object the given condition accept.conditions - the conditions to evaluate.AnyOf.public static <T> Condition<T> anyOf(Iterable<? extends Condition<? super T>> conditions)
AnyOfT - the type of object the given condition accept.conditions - the conditions to evaluate.AnyOf.NullPointerException - if the given iterable is null.NullPointerException - if any of the elements in the given iterable is null.public static <T> DoesNotHave<T> doesNotHave(Condition<? super T> condition)
DoesNotHave.T - the type of object the given condition accept.condition - the condition to inverse.public static <T> Not<T> not(Condition<? super T> condition)
Not.T - the type of object the given condition accept.condition - the condition to inverse.public static InFilter in(Object... values)
FilterOperator to use in filteredOn(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);values - values to match (one match is sufficient)public static NotInFilter notIn(Object... valuesNotToMatch)
FilterOperator to use in filteredOn(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);valuesNotToMatch - values not to match (none of the values must match)public static NotFilter not(Object valueNotToMatch)
FilterOperator to use in filteredOn(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);valueNotToMatch - the value not to matchpublic static String contentOf(File file, Charset charset)
Assertions.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).
file - the file.charset - the character set to use.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static String contentOf(File file, String charsetName)
Assertions.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).
file - the file.charsetName - the name of the character set to use.IllegalArgumentException - if the given character set is not supported on this platform.UncheckedIOException - if an I/O exception occurs.public static String contentOf(File file)
Assertions.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).
file - the file.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(File file)
file - the file.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(File file, Charset charset)
file - the file.charset - the character set to use.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(File file, String charsetName)
file - the file.charsetName - the name of the character set to use.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(Path path)
path - the path.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(Path path, Charset charset)
path - the path.charset - the character set to use.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(Path path, String charsetName)
path - the path.charsetName - the name of the character set to use.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static String contentOf(URL url, Charset charset)
Assertions.assertThat(String).
Note that this will load the entire contents in memory.
url - the URL.charset - the character set to use.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static String contentOf(URL url, String charsetName)
Assertions.assertThat(String).
Note that this will load the entire contents in memory.
url - the URL.charsetName - the name of the character set to use.IllegalArgumentException - if the given character set is not supported on this platform.UncheckedIOException - if an I/O exception occurs.public static String contentOf(URL url)
Assertions.assertThat(String).
Note that this will load the entire file in memory; for larger files.
url - the URL.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(URL url)
url - the URL.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(URL url, Charset charset)
url - the URL.charset - the character set to use.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static List<String> linesOf(URL url, String charsetName)
url - the URL.charsetName - the name of the character set to use.NullPointerException - if the given charset is null.UncheckedIOException - if an I/O exception occurs.public static void setLenientDateParsing(boolean value)
With strict parsing, inputs must match exactly date/time format.
Example:
final 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
To revert to default strict date parsing, call setLenientDateParsing(false).value - whether lenient parsing mode should be enabled or notpublic static void registerCustomDateFormat(DateFormat userCustomDateFormat)
AbstractDateAssert.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() or
AbstractDateAssert.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");userCustomDateFormat - the new Date format used for String based Date assertions.public static void registerCustomDateFormat(String userCustomDateFormatPattern)
AbstractDateAssert.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() or
AbstractDateAssert.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");userCustomDateFormatPattern - the new Date format pattern used for String based Date assertions.public static void useDefaultDateFormatsOnly()
Beware that the default formats are expressed in the current local timezone.
Defaults date format are:
yyyy-MM-dd HH:mm:ss.SSSXyyyy-MM-dd'T'HH:mm:ss.SSSyyyy-MM-dd HH:mm:ss.SSS (for Timestamp String representation support)yyyy-MM-dd'T'HH:mm:ssXyyyy-MM-dd'T'HH:mm:ssyyyy-MM-ddExample of valid string date representations:
2003-04-26T03:01:02.9992003-04-26 03:01:02.9992003-04-26T13:01:022003-04-26public static void useRepresentation(Representation customRepresentation)
Representation 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 globally
Example :
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$>customRepresentation - the Representation to usepublic static <T> void registerFormatterForType(Class<T> type, Function<T,String> formatter)
Representation 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);T - the type of format.type - the class of the type to formatformatter - the formatter Functionpublic static void useDefaultRepresentation()
StandardRepresentation to revert the effect of calling useRepresentation(Representation).Copyright © 2025. All rights reserved.