Class Assertions
- java.lang.Object
-
- org.assertj.core.api.Assertions
-
- Direct Known Subclasses:
BDDAssertions
public class Assertions extends java.lang.Object
Entry point for assertion methods for different types. Each method in this class is a static factory for a type-specific assertion object.For example:
This class only contains allint removed = employees.removeFired();
assertThat
(removed).isZero
(); List<Employee> newEmployees = employees.hired(TODAY);assertThat
(newEmployees).hasSize
(6);assertThat
methods, if you have ambiguous method compilation error, use eitherAssertionsForClassTypes
orAssertionsForInterfaceTypes
and if you need both, fully qualify you assertThat method. Java 8 is picky when choosing the rightassertThat
method if the object under test is generic and bounded, for example if foo is instance of T that extends Exception, java 8 will complain that it can't resolve the properassertThat
method (normallyassertThat(Throwable)
as foo might implement an interface like List, if that occurredassertThat(List)
would also be a possible choice - thus confusing java 8.This why
Assertions
have been split inAssertionsForClassTypes
andAssertionsForInterfaceTypes
(see http://stackoverflow.com/questions/29499847/ambiguous-method-in-java-8-why).
-
-
Constructor Summary
Constructors Modifier Constructor Description protected
Assertions()
Creates a newAssertions
.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <T> Condition<T>
allOf(java.lang.Iterable<? extends Condition<? super T>> conditions)
Creates a newAllOf
static <T> Condition<T>
allOf(Condition<? super T>... conditions)
Creates a newAllOf
static <T> Condition<T>
anyOf(java.lang.Iterable<? extends Condition<? super T>> conditions)
Creates a newAnyOf
static <T> Condition<T>
anyOf(Condition<? super T>... conditions)
Only delegate toAnyOf.anyOf(Condition...)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useAnyOf
if you prefer).static AbstractBooleanAssert<?>
assertThat(boolean actual)
Creates a new instance of
.BooleanAssert
static AbstractBooleanArrayAssert<?>
assertThat(boolean[] actual)
Creates a new instance of
.BooleanArrayAssert
static AbstractByteAssert<?>
assertThat(byte actual)
Creates a new instance of
.ByteAssert
static AbstractByteArrayAssert<?>
assertThat(byte[] actual)
Creates a new instance of
.ByteArrayAssert
static AbstractCharacterAssert<?>
assertThat(char actual)
Creates a new instance of
.CharacterAssert
static AbstractCharArrayAssert<?>
assertThat(char[] actual)
Creates a new instance of
.CharArrayAssert
static AbstractDoubleAssert<?>
assertThat(double actual)
Creates a new instance of
.DoubleAssert
static AbstractDoubleArrayAssert<?>
assertThat(double[] actual)
Creates a new instance of
.DoubleArrayAssert
static AbstractFloatAssert<?>
assertThat(float actual)
Creates a new instance of
.FloatAssert
static AbstractFloatArrayAssert<?>
assertThat(float[] actual)
Creates a new instance of
.FloatArrayAssert
static AbstractIntegerAssert<?>
assertThat(int actual)
Creates a new instance of
.IntegerAssert
static AbstractIntArrayAssert<?>
assertThat(int[] actual)
Creates a new instance of
.IntArrayAssert
static AbstractLongAssert<?>
assertThat(long actual)
Creates a new instance of
.LongAssert
static AbstractLongArrayAssert<?>
assertThat(long[] actual)
Creates a new instance of
.LongArrayAssert
static AbstractShortAssert<?>
assertThat(short actual)
Creates a new instance of
.ShortAssert
static AbstractShortArrayAssert<?>
assertThat(short[] actual)
Creates a new instance of
.ShortArrayAssert
static <ACTUAL extends java.lang.Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
ClassBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT>assertThat(ACTUAL actual, java.lang.Class<ELEMENT_ASSERT> assertClass)
Creates a new instance of
allowing to navigate to anyClassBasedNavigableIterableAssert
Iterable
element in order to perform assertions on it.static AbstractFileAssert<?>
assertThat(java.io.File actual)
Creates a new instance of
.FileAssert
static AbstractInputStreamAssert<?,? extends java.io.InputStream>
assertThat(java.io.InputStream actual)
Creates a new instance of
.InputStreamAssert
static AbstractBooleanAssert<?>
assertThat(java.lang.Boolean actual)
Creates a new instance of
.BooleanAssert
static AbstractByteAssert<?>
assertThat(java.lang.Byte actual)
Creates a new instance of
.ByteAssert
static AbstractCharacterAssert<?>
assertThat(java.lang.Character actual)
Creates a new instance of
.CharacterAssert
static AbstractCharSequenceAssert<?,? extends java.lang.CharSequence>
assertThat(java.lang.CharSequence actual)
Creates a new instance of
.CharSequenceAssert
static AbstractClassAssert<?>
assertThat(java.lang.Class<?> actual)
Creates a new instance ofClassAssert
static AbstractDoubleAssert<?>
assertThat(java.lang.Double actual)
Creates a new instance of
.DoubleAssert
static AbstractFloatAssert<?>
assertThat(java.lang.Float actual)
Creates a new instance of
.FloatAssert
static AbstractIntegerAssert<?>
assertThat(java.lang.Integer actual)
Creates a new instance of
.IntegerAssert
static <ELEMENT> IterableAssert<ELEMENT>
assertThat(java.lang.Iterable<? extends ELEMENT> actual)
Creates a new instance of
.IterableAssert
static <ACTUAL extends java.lang.Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
FactoryBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT>assertThat(java.lang.Iterable<? extends ELEMENT> actual, AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)
Creates a new instance of
allowing to navigate to anyFactoryBasedNavigableIterableAssert
Iterable
element in order to perform assertions on it.static AbstractLongAssert<?>
assertThat(java.lang.Long actual)
Creates a new instance of
.LongAssert
static AbstractShortAssert<?>
assertThat(java.lang.Short actual)
Creates a new instance of
.ShortAssert
static AbstractCharSequenceAssert<?,java.lang.String>
assertThat(java.lang.String actual)
Creates a new instance of
.StringAssert
static AbstractThrowableAssert<?,? extends java.lang.Throwable>
assertThat(java.lang.Throwable actual)
Creates a new instance of
.ThrowableAssert
static AbstractBigDecimalAssert<?>
assertThat(java.math.BigDecimal actual)
Creates a new instance of
.BigDecimalAssert
static AbstractBigIntegerAssert<?>
assertThat(java.math.BigInteger actual)
Creates a new instance of
.BigIntegerAssert
static AbstractUriAssert<?>
assertThat(java.net.URI actual)
Creates a new instance of
.UriAssert
static AbstractUrlAssert<?>
assertThat(java.net.URL actual)
Creates a new instance of
.UrlAssert
static AbstractPathAssert<?>
assertThat(java.nio.file.Path actual)
Creates a new instance ofPathAssert
static AbstractInstantAssert<?>
assertThat(java.time.Instant actual)
Creates a new instance of
.InstantAssert
static AbstractLocalDateAssert<?>
assertThat(java.time.LocalDate actual)
Creates a new instance of
.LocalDateAssert
static AbstractLocalDateTimeAssert<?>
assertThat(java.time.LocalDateTime actual)
Creates a new instance of
.LocalDateTimeAssert
static AbstractLocalTimeAssert<?>
assertThat(java.time.LocalTime actual)
Creates a new instance of
.LocalTimeAssert
static AbstractOffsetDateTimeAssert<?>
assertThat(java.time.OffsetDateTime actual)
Creates a new instance of
.OffsetDateTime
static AbstractOffsetTimeAssert<?>
assertThat(java.time.OffsetTime actual)
Create assertion forOffsetTime
.static AbstractZonedDateTimeAssert<?>
assertThat(java.time.ZonedDateTime actual)
Creates a new instance of
.ZonedDateTimeAssert
static AtomicBooleanAssert
assertThat(java.util.concurrent.atomic.AtomicBoolean actual)
Create assertion forAtomicBoolean
.static AtomicIntegerAssert
assertThat(java.util.concurrent.atomic.AtomicInteger actual)
Create assertion forAtomicInteger
.static AtomicIntegerArrayAssert
assertThat(java.util.concurrent.atomic.AtomicIntegerArray actual)
Create int[] assertion forAtomicIntegerArray
.static <OBJECT> AtomicIntegerFieldUpdaterAssert<OBJECT>
assertThat(java.util.concurrent.atomic.AtomicIntegerFieldUpdater<OBJECT> actual)
Create assertion forAtomicIntegerFieldUpdater
.static AtomicLongAssert
assertThat(java.util.concurrent.atomic.AtomicLong actual)
Create assertion forAtomicLong
.static AtomicLongArrayAssert
assertThat(java.util.concurrent.atomic.AtomicLongArray actual)
Create assertion forAtomicLongArray
.static <OBJECT> AtomicLongFieldUpdaterAssert<OBJECT>
assertThat(java.util.concurrent.atomic.AtomicLongFieldUpdater<OBJECT> actual)
Create assertion forAtomicLongFieldUpdater
.static <VALUE> AtomicMarkableReferenceAssert<VALUE>
assertThat(java.util.concurrent.atomic.AtomicMarkableReference<VALUE> actual)
Create assertion forAtomicMarkableReference
.static <VALUE> AtomicReferenceAssert<VALUE>
assertThat(java.util.concurrent.atomic.AtomicReference<VALUE> actual)
Create assertion forAtomicReference
.static <ELEMENT> AtomicReferenceArrayAssert<ELEMENT>
assertThat(java.util.concurrent.atomic.AtomicReferenceArray<ELEMENT> actual)
Create assertion forAtomicReferenceArray
.static <FIELD,OBJECT>
AtomicReferenceFieldUpdaterAssert<FIELD,OBJECT>assertThat(java.util.concurrent.atomic.AtomicReferenceFieldUpdater<OBJECT,FIELD> actual)
Create assertion forAtomicReferenceFieldUpdater
.static <VALUE> AtomicStampedReferenceAssert<VALUE>
assertThat(java.util.concurrent.atomic.AtomicStampedReference<VALUE> actual)
Create assertion forAtomicStampedReference
.static <RESULT> CompletableFutureAssert<RESULT>
assertThat(java.util.concurrent.CompletableFuture<RESULT> actual)
Create assertion forCompletableFuture
.static <RESULT> AbstractFutureAssert<?,? extends java.util.concurrent.Future<? extends RESULT>,RESULT>
assertThat(java.util.concurrent.Future<RESULT> actual)
Create assertion forFuture
.static AbstractDateAssert<?>
assertThat(java.util.Date actual)
Creates a new instance of
.DateAssert
static DoublePredicateAssert
assertThat(java.util.function.DoublePredicate actual)
Create assertion forDoublePredicate
.static IntPredicateAssert
assertThat(java.util.function.IntPredicate actual)
Create assertion forIntPredicate
.static LongPredicateAssert
assertThat(java.util.function.LongPredicate actual)
Create assertion forLongPredicate
.static <T> PredicateAssert<T>
assertThat(java.util.function.Predicate<T> actual)
Create assertion forPredicate
.static <ELEMENT> IterableAssert<ELEMENT>
assertThat(java.util.Iterator<? extends ELEMENT> actual)
Creates a new instance of
.IterableAssert
static <ELEMENT> ListAssert<ELEMENT>
assertThat(java.util.List<? extends ELEMENT> actual)
Creates a new instance of
.ListAssert
static <ELEMENT,ACTUAL extends java.util.List<? extends ELEMENT>,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
ClassBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT>assertThat(java.util.List<? extends ELEMENT> actual, java.lang.Class<ELEMENT_ASSERT> assertClass)
Creates a new instance of
tallowing to navigate to anyClassBasedNavigableListAssert
List
element in order to perform assertions on it.static <ACTUAL extends java.util.List<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>>
FactoryBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT>assertThat(java.util.List<? extends ELEMENT> actual, AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)
Creates a new instance of
allowing to navigate to anyFactoryBasedNavigableListAssert
List
element in order to perform assertions on it.static <K,V>
MapAssert<K,V>assertThat(java.util.Map<K,V> actual)
Creates a new instance of
.MapAssert
static <VALUE> OptionalAssert<VALUE>
assertThat(java.util.Optional<VALUE> actual)
Create assertion forOptional
.static OptionalDoubleAssert
assertThat(java.util.OptionalDouble actual)
Create assertion forOptionalDouble
.static OptionalIntAssert
assertThat(java.util.OptionalInt actual)
Create assertion forOptionalInt
.static OptionalLongAssert
assertThat(java.util.OptionalLong actual)
Create assertion forOptionalInt
.static <ELEMENT,STREAM extends java.util.stream.BaseStream<ELEMENT,STREAM>>
AbstractListAssert<?,java.util.List<? extends ELEMENT>,ELEMENT,ObjectAssert<ELEMENT>>assertThat(java.util.stream.BaseStream<? extends ELEMENT,STREAM> actual)
Creates a new instance of
from the givenListAssert
BaseStream
.static <T> T
assertThat(AssertProvider<T> component)
Delegates the creation of theAssert
to theAssertProvider.assertThat()
of the given component.static <T> AbstractObjectAssert<?,T>
assertThat(T actual)
Creates a new instance of
.ObjectAssert
static <T> AbstractObjectArrayAssert<?,T>
assertThat(T[] actual)
Creates a new instance of
.ObjectArrayAssert
static AbstractThrowableAssert<?,? extends java.lang.Throwable>
assertThatCode(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable)
Allows to capture and then assert on aThrowable
more easily when used with Java 8 lambdas.static <T extends java.lang.Throwable>
ThrowableTypeAssert<T>assertThatExceptionOfType(java.lang.Class<? extends T> exceptionType)
Entry point to check that an exception of type T is thrown by a giventhrowingCallable
which allows to chain assertions on the thrown exception.static ThrowableTypeAssert<java.lang.IllegalArgumentException>
assertThatIllegalArgumentException()
Alias forassertThatExceptionOfType(Class)
forIllegalArgumentException
.static ThrowableTypeAssert<java.lang.IllegalStateException>
assertThatIllegalStateException()
Alias forassertThatExceptionOfType(Class)
forIllegalStateException
.static ThrowableTypeAssert<java.io.IOException>
assertThatIOException()
Alias forassertThatExceptionOfType(Class)
forIOException
.static ThrowableTypeAssert<java.lang.NullPointerException>
assertThatNullPointerException()
Alias forassertThatExceptionOfType(Class)
forNullPointerException
.static AbstractThrowableAssert<?,? extends java.lang.Throwable>
assertThatThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Allows to capture and then assert on aThrowable
more easily when used with Java 8 lambdas.static Index
atIndex(int index)
Only delegate toIndex.atIndex(int)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useIndex
if you prefer).static TemporalUnitOffset
byLessThan(long value, java.time.temporal.TemporalUnit unit)
Assertions entry point forTemporalUnitOffset
with strict less than condition to use withisCloseTo
temporal assertions.static Offset<java.lang.Byte>
byLessThan(java.lang.Byte value)
Assertions entry point for ByteOffset
to use with isCloseTo assertions.static Offset<java.lang.Double>
byLessThan(java.lang.Double value)
Alias foroffset(Double)
to use with isCloseTo assertions.static Offset<java.lang.Float>
byLessThan(java.lang.Float value)
Alias foroffset(Float)
to use with isCloseTo assertions.static Offset<java.lang.Integer>
byLessThan(java.lang.Integer value)
Assertions entry point for IntegerOffset
to use with isCloseTo assertions.static Offset<java.lang.Long>
byLessThan(java.lang.Long value)
Assertions entry point for LongOffset
to use with isCloseTo assertions.static Offset<java.lang.Short>
byLessThan(java.lang.Short value)
Assertions entry point for ShortOffset
to use with isCloseTo assertions.static Offset<java.math.BigDecimal>
byLessThan(java.math.BigDecimal value)
Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.static Offset<java.math.BigInteger>
byLessThan(java.math.BigInteger value)
Assertions entry point for BigIntegerOffset
to use with isCloseTo assertions.static java.lang.Throwable
catchThrowable(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Allows to catch anThrowable
more easily when used with Java 8 lambdas.static java.lang.String
contentOf(java.io.File file)
Loads the text content of a file with the default character set, so that it can be passed toassertThat(String)
.static java.lang.String
contentOf(java.io.File file, java.lang.String charsetName)
Loads the text content of a file, so that it can be passed toassertThat(String)
.static java.lang.String
contentOf(java.io.File file, java.nio.charset.Charset charset)
Loads the text content of a file, so that it can be passed toassertThat(String)
.static java.lang.String
contentOf(java.net.URL url)
Loads the text content of a URL with the default character set, so that it can be passed toassertThat(String)
.static java.lang.String
contentOf(java.net.URL url, java.lang.String charsetName)
Loads the text content of a URL, so that it can be passed toassertThat(String)
.static java.lang.String
contentOf(java.net.URL url, java.nio.charset.Charset charset)
Loads the text content of a URL, so that it can be passed toassertThat(String)
.static <T> DoesNotHave<T>
doesNotHave(Condition<? super T> condition)
Creates a newDoesNotHave
.static <K,V>
MapEntry<K,V>entry(K key, V value)
Only delegate toMapEntry.entry(Object, Object)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useMapEntry
if you prefer).static Properties<java.lang.Object>
extractProperty(java.lang.String propertyName)
Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).static <T> Properties<T>
extractProperty(java.lang.String propertyName, java.lang.Class<T> propertyType)
Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).static void
fail(java.lang.String failureMessage)
Throws anAssertionError
with the given message.static void
fail(java.lang.String failureMessage, java.lang.Object... args)
Throws anAssertionError
with the given message built asString.format(String, Object...)
.static void
fail(java.lang.String failureMessage, java.lang.Throwable realCause)
Throws anAssertionError
with the given message and with theThrowable
that caused the failure.static void
failBecauseExceptionWasNotThrown(java.lang.Class<? extends java.lang.Throwable> throwableClass)
Throws anAssertionError
with a message explaining that aThrowable
of given class was expected to be thrown but had not been.static <E> Filters<E>
filter(E[] array)
Only delegate toFilters.filter(Object[])
so that Assertions offers a full feature entry point to all AssertJ features (but you can useFilters
if you prefer).static <E> Filters<E>
filter(java.lang.Iterable<E> iterableToFilter)
Only delegate toFilters.filter(Object[])
so that Assertions offers a full feature entry point to all AssertJ features (but you can useFilters
if you prefer).static <F,T>
java.util.function.Function<F,T>from(java.util.function.Function<F,T> extractor)
A syntax sugar to write fluent assertion usingAbstractObjectAssert.returns(Object, Function)
.static InFilter
in(java.lang.Object... values)
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches one of the given values.static java.util.List<java.lang.String>
linesOf(java.io.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 java.util.List<java.lang.String>
linesOf(java.io.File file, java.lang.String charsetName)
Loads the text content of a file into a list of strings, each string corresponding to a line.static java.util.List<java.lang.String>
linesOf(java.io.File file, java.nio.charset.Charset charset)
Loads the text content of a file into a list of strings, each string corresponding to a line.static java.util.List<java.lang.String>
linesOf(java.net.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 java.util.List<java.lang.String>
linesOf(java.net.URL url, java.lang.String charsetName)
Loads the text content of a URL into a list of strings, each string corresponding to a line.static java.util.List<java.lang.String>
linesOf(java.net.URL url, java.nio.charset.Charset charset)
Loads the text content of a URL into a list of strings, each string corresponding to a line.static NotFilter
not(java.lang.Object valueNotToMatch)
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches does not match the given value.static <T> Not<T>
not(Condition<? super T> condition)
Creates a newNot
.static NotInFilter
notIn(java.lang.Object... valuesNotToMatch)
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches does not match any of the given values.static Offset<java.lang.Double>
offset(java.lang.Double value)
Assertions entry point for doubleOffset
.static Offset<java.lang.Float>
offset(java.lang.Float value)
Assertions entry point for floatOffset
.static void
registerCustomDateFormat(java.lang.String userCustomDateFormatPattern)
Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String)
.static void
registerCustomDateFormat(java.text.DateFormat userCustomDateFormat)
Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String)
.static <T> void
registerFormatterForType(java.lang.Class<T> type, java.util.function.Function<T,java.lang.String> formatter)
Assertions error messages uses aRepresentation
to format the different types involved, using this method you can control the formatting of a given type by providing a specific formatter.static void
setAllowComparingPrivateFields(boolean allowComparingPrivateFields)
Globally sets whether the use of private fields is allowed for comparison.static void
setAllowExtractingPrivateFields(boolean allowExtractingPrivateFields)
Globally sets whether
andIterableAssert#extracting(String)
should be allowed to extract private fields, if not and they try it fails with exception.ObjectArrayAssert#extracting(String)
static void
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)
In error messages, sets the threshold for how many elements from one iterable/array/map will be included in the in the description.static void
setMaxLengthForSingleLineDescription(int maxLengthForSingleLineDescription)
In error messages, sets the threshold when iterable/array formatting will on one line (if their String description is less than this parameter) or it will be formatted with one element per line.static void
setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace)
Sets whether we remove elements related to AssertJ from assertion error stack trace.static void
shouldHaveThrown(java.lang.Class<? extends java.lang.Throwable> throwableClass)
Throws anAssertionError
with a message explaining that aThrowable
of given class was expected to be thrown but had not been.static Tuple
tuple(java.lang.Object... values)
Utility method to build nicely aTuple
when working withAbstractIterableAssert.extracting(String...)
orAbstractObjectArrayAssert.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 useStandardRepresentation
to revert the effect of callinguseRepresentation(Representation)
.static void
useRepresentation(Representation customRepresentation)
Register aRepresentation
that will be used in all following assertions.static TemporalUnitOffset
within(long value, java.time.temporal.TemporalUnit unit)
Assertions entry point forTemporalUnitOffset
with with less than or equal condition to use with isCloseTo temporal assertions.static Offset<java.lang.Byte>
within(java.lang.Byte value)
Assertions entry point for ByteOffset
to use with isCloseTo assertions.static Offset<java.lang.Double>
within(java.lang.Double value)
Alias foroffset(Double)
to use with isCloseTo assertions.static Offset<java.lang.Float>
within(java.lang.Float value)
Alias foroffset(Float)
to use with isCloseTo assertions.static Offset<java.lang.Integer>
within(java.lang.Integer value)
Assertions entry point for IntegerOffset
to use with isCloseTo assertions.static Offset<java.lang.Long>
within(java.lang.Long value)
Assertions entry point for LongOffset
to use with isCloseTo assertions.static Offset<java.lang.Short>
within(java.lang.Short value)
Assertions entry point for ShortOffset
to use with isCloseTo assertions.static Offset<java.math.BigDecimal>
within(java.math.BigDecimal value)
Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.static Offset<java.math.BigInteger>
within(java.math.BigInteger value)
Assertions entry point for BigIntegerOffset
to use with isCloseTo assertions.static Percentage
withinPercentage(java.lang.Double value)
Assertions entry point for DoublePercentage
to use with isCloseTo assertions for percentages.static Percentage
withinPercentage(java.lang.Integer value)
Assertions entry point for IntegerPercentage
to use with isCloseTo assertions for percentages.static Percentage
withinPercentage(java.lang.Long value)
Assertions entry point for LongPercentage
to use with isCloseTo assertions for percentages.static Offset<java.lang.Double>
withPrecision(java.lang.Double value)
Alias foroffset(Double)
to use with real number assertions.static Offset<java.lang.Float>
withPrecision(java.lang.Float value)
Alias foroffset(Float)
to use with real number assertions.
-
-
-
Constructor Detail
-
Assertions
protected Assertions()
Creates a newAssertions
.
-
-
Method Detail
-
assertThat
public static <T> PredicateAssert<T> assertThat(java.util.function.Predicate<T> actual)
Create assertion forPredicate
.- Type Parameters:
T
- the type of the value contained in thePredicate
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.5.0
-
assertThat
public static IntPredicateAssert assertThat(java.util.function.IntPredicate actual)
Create assertion forIntPredicate
.- Returns:
- the created assertion object.
- Since:
- 3.5.0
-
assertThat
public static LongPredicateAssert assertThat(java.util.function.LongPredicate actual)
Create assertion forLongPredicate
.- Returns:
- the created assertion object.
- Since:
- 3.5.0
-
assertThat
public static DoublePredicateAssert assertThat(java.util.function.DoublePredicate actual)
Create assertion forDoublePredicate
.- Returns:
- the created assertion object.
- Since:
- 3.5.0
-
assertThat
public static <RESULT> CompletableFutureAssert<RESULT> assertThat(java.util.concurrent.CompletableFuture<RESULT> actual)
Create assertion forCompletableFuture
.- Type Parameters:
RESULT
- the type of the value contained in theCompletableFuture
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <VALUE> OptionalAssert<VALUE> assertThat(java.util.Optional<VALUE> actual)
Create assertion forOptional
.- Type Parameters:
VALUE
- the type of the value contained in theOptional
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static OptionalDoubleAssert assertThat(java.util.OptionalDouble actual)
Create assertion forOptionalDouble
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static OptionalIntAssert assertThat(java.util.OptionalInt actual)
Create assertion forOptionalInt
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static OptionalLongAssert assertThat(java.util.OptionalLong actual)
Create assertion forOptionalInt
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractBigDecimalAssert<?> assertThat(java.math.BigDecimal actual)
Creates a new instance of
.BigDecimalAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractBigIntegerAssert<?> assertThat(java.math.BigInteger actual)
Creates a new instance of
.BigIntegerAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static AbstractUriAssert<?> assertThat(java.net.URI actual)
Creates a new instance of
.UriAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractUrlAssert<?> assertThat(java.net.URL actual)
Creates a new instance of
.UrlAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractBooleanAssert<?> assertThat(boolean actual)
Creates a new instance of
.BooleanAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractBooleanAssert<?> assertThat(java.lang.Boolean actual)
Creates a new instance of
.BooleanAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractBooleanArrayAssert<?> assertThat(boolean[] actual)
Creates a new instance of
.BooleanArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractByteAssert<?> assertThat(byte actual)
Creates a new instance of
.ByteAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractByteAssert<?> assertThat(java.lang.Byte actual)
Creates a new instance of
.ByteAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractByteArrayAssert<?> assertThat(byte[] actual)
Creates a new instance of
.ByteArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractCharacterAssert<?> assertThat(char actual)
Creates a new instance of
.CharacterAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractCharArrayAssert<?> assertThat(char[] actual)
Creates a new instance of
.CharArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractCharacterAssert<?> assertThat(java.lang.Character actual)
Creates a new instance of
.CharacterAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractClassAssert<?> assertThat(java.lang.Class<?> actual)
Creates a new instance ofClassAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractDoubleAssert<?> assertThat(double actual)
Creates a new instance of
.DoubleAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractDoubleAssert<?> assertThat(java.lang.Double actual)
Creates a new instance of
.DoubleAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractDoubleArrayAssert<?> assertThat(double[] actual)
Creates a new instance of
.DoubleArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractFileAssert<?> assertThat(java.io.File actual)
Creates a new instance of
.FileAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <RESULT> AbstractFutureAssert<?,? extends java.util.concurrent.Future<? extends RESULT>,RESULT> assertThat(java.util.concurrent.Future<RESULT> actual)
Create assertion forFuture
.- Type Parameters:
RESULT
- the type of the value contained in theFuture
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static AbstractInputStreamAssert<?,? extends java.io.InputStream> assertThat(java.io.InputStream actual)
Creates a new instance of
.InputStreamAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractFloatAssert<?> assertThat(float actual)
Creates a new instance of
.FloatAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractFloatAssert<?> assertThat(java.lang.Float actual)
Creates a new instance of
.FloatAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractFloatArrayAssert<?> assertThat(float[] actual)
Creates a new instance of
.FloatArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractIntegerAssert<?> assertThat(int actual)
Creates a new instance of
.IntegerAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractIntArrayAssert<?> assertThat(int[] actual)
Creates a new instance of
.IntArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractIntegerAssert<?> assertThat(java.lang.Integer actual)
Creates a new instance of
.IntegerAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <ACTUAL extends java.lang.Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> FactoryBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> assertThat(java.lang.Iterable<? extends ELEMENT> actual, AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)
Creates a new instance of
allowing to navigate to anyFactoryBasedNavigableIterableAssert
Iterable
element in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the
ELEMENT_ASSERT
parameter of the givenAssertFactory<ELEMENT, ELEMENT_ASSERT>
(AssertJ can't figure it out because of Java type erasure).Example with
String
element assertions:Iterable<String> hobbits = newHashSet("frodo", "sam", "pippin"); // build an AssertFactory for StringAssert (much nicer with Java 8 lambdas) AssertFactory<String, StringAssert> stringAssertFactory = new AssertFactory<String, StringAssert>() { @Override public StringAssert createAssert(String string) { return new StringAssert(string); } }; // assertion succeeds with String assertions chained after first() assertThat(hobbits, stringAssertFactory).first() .startsWith("fro") .endsWith("do");
- Parameters:
actual
- the actual value.assertFactory
- the factory used to create the elements assert instance.- Returns:
- the created assertion object.
- Since:
- 2.5.0 / 3.5.0
-
assertThat
public static <ACTUAL extends java.lang.Iterable<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> ClassBasedNavigableIterableAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> assertThat(ACTUAL actual, java.lang.Class<ELEMENT_ASSERT> assertClass)
Creates a new instance of
allowing to navigate to anyClassBasedNavigableIterableAssert
Iterable
element in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the given
assertClass
(AssertJ can't find the element assert type by itself because of Java type erasure).Example with
String
element assertions:Iterable<String> hobbits = newHashSet("frodo", "sam", "pippin"); // assertion succeeds with String assertions chained after first() assertThat(hobbits, StringAssert.class).first() .startsWith("fro") .endsWith("do");
- Parameters:
actual
- the actual value.assertClass
- the class used to create the elements assert instance.- Returns:
- the created assertion object.
- Since:
- 2.5.0 / 3.5.0
-
assertThat
public static <ACTUAL extends java.util.List<? extends ELEMENT>,ELEMENT,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> FactoryBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> assertThat(java.util.List<? extends ELEMENT> actual, AssertFactory<ELEMENT,ELEMENT_ASSERT> assertFactory)
Creates a new instance of
allowing to navigate to anyFactoryBasedNavigableListAssert
List
element in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the
ELEMENT_ASSERT
parameter of the givenAssertFactory<ELEMENT, ELEMENT_ASSERT>
(AssertJ can't figure it out because of Java type erasure).Example with
String
element assertions:List<String> hobbits = newArrayList("frodo", "sam", "pippin"); // build an AssertFactory for StringAssert (much nicer with Java 8 lambdas) AssertFactory<String, StringAssert> stringAssertFactory = new AssertFactory<String, StringAssert>() { @Override public StringAssert createAssert(String string) { return new StringAssert(string); } }; // assertion succeeds with String assertions chained after first() assertThat(hobbits, stringAssertFactory).first() .startsWith("fro") .endsWith("do");
- Parameters:
actual
- the actual value.assertFactory
- the factory used to create the elements assert instance.- Returns:
- the created assertion object.
- Since:
- 2.5.0 / 3.5.0
-
assertThat
public static <ELEMENT,ACTUAL extends java.util.List<? extends ELEMENT>,ELEMENT_ASSERT extends AbstractAssert<ELEMENT_ASSERT,ELEMENT>> ClassBasedNavigableListAssert<?,ACTUAL,ELEMENT,ELEMENT_ASSERT> assertThat(java.util.List<? extends ELEMENT> actual, java.lang.Class<ELEMENT_ASSERT> assertClass)
Creates a new instance of
tallowing to navigate to anyClassBasedNavigableListAssert
List
element in order to perform assertions on it.Navigational methods provided:
The available assertions after navigating to an element depend on the given
assertClass
(AssertJ can't find the element assert type by itself because of Java type erasure).Example with
String
element assertions:List<String> hobbits = newArrayList("frodo", "sam", "pippin"); // assertion succeeds with String assertions chained after first() assertThat(hobbits, StringAssert.class).first() .startsWith("fro") .endsWith("do");
- Parameters:
actual
- the actual value.assertClass
- the class used to create the elements assert instance.- Returns:
- the created assertion object.
- Since:
- 2.5.0 / 3.5.0
-
assertThat
public static AbstractLongAssert<?> assertThat(long actual)
Creates a new instance of
.LongAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractLongAssert<?> assertThat(java.lang.Long actual)
Creates a new instance of
.LongAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractLongArrayAssert<?> assertThat(long[] actual)
Creates a new instance of
.LongArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <T> AbstractObjectAssert<?,T> assertThat(T actual)
Creates a new instance of
.ObjectAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <T> AbstractObjectArrayAssert<?,T> assertThat(T[] actual)
Creates a new instance of
.ObjectArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractShortAssert<?> assertThat(short actual)
Creates a new instance of
.ShortAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractShortAssert<?> assertThat(java.lang.Short actual)
Creates a new instance of
.ShortAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractShortArrayAssert<?> assertThat(short[] actual)
Creates a new instance of
.ShortArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractCharSequenceAssert<?,java.lang.String> assertThat(java.lang.String actual)
Creates a new instance of
.StringAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractDateAssert<?> assertThat(java.util.Date actual)
Creates a new instance of
.DateAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractZonedDateTimeAssert<?> assertThat(java.time.ZonedDateTime actual)
Creates a new instance of
.ZonedDateTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractLocalDateTimeAssert<?> assertThat(java.time.LocalDateTime actual)
Creates a new instance of
.LocalDateTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractOffsetDateTimeAssert<?> assertThat(java.time.OffsetDateTime actual)
Creates a new instance of
.OffsetDateTime
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractOffsetTimeAssert<?> assertThat(java.time.OffsetTime actual)
Create assertion forOffsetTime
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractLocalTimeAssert<?> assertThat(java.time.LocalTime actual)
Creates a new instance of
.LocalTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractLocalDateAssert<?> assertThat(java.time.LocalDate actual)
Creates a new instance of
.LocalDateAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractInstantAssert<?> assertThat(java.time.Instant actual)
Creates a new instance of
.InstantAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.7.0
-
assertThat
public static AtomicBooleanAssert assertThat(java.util.concurrent.atomic.AtomicBoolean actual)
Create assertion forAtomicBoolean
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static AtomicIntegerAssert assertThat(java.util.concurrent.atomic.AtomicInteger actual)
Create assertion forAtomicInteger
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static AtomicIntegerArrayAssert assertThat(java.util.concurrent.atomic.AtomicIntegerArray actual)
Create int[] assertion forAtomicIntegerArray
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static <OBJECT> AtomicIntegerFieldUpdaterAssert<OBJECT> assertThat(java.util.concurrent.atomic.AtomicIntegerFieldUpdater<OBJECT> actual)
Create assertion forAtomicIntegerFieldUpdater
.- Type Parameters:
OBJECT
- the type of the object holding the updatable field.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static AtomicLongAssert assertThat(java.util.concurrent.atomic.AtomicLong actual)
Create assertion forAtomicLong
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static AtomicLongArrayAssert assertThat(java.util.concurrent.atomic.AtomicLongArray actual)
Create assertion forAtomicLongArray
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static <OBJECT> AtomicLongFieldUpdaterAssert<OBJECT> assertThat(java.util.concurrent.atomic.AtomicLongFieldUpdater<OBJECT> actual)
Create assertion forAtomicLongFieldUpdater
.- Type Parameters:
OBJECT
- the type of the object holding the updatable field.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static <VALUE> AtomicReferenceAssert<VALUE> assertThat(java.util.concurrent.atomic.AtomicReference<VALUE> actual)
Create assertion forAtomicReference
.- Type Parameters:
VALUE
- the type of the value contained in theAtomicReference
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static <ELEMENT> AtomicReferenceArrayAssert<ELEMENT> assertThat(java.util.concurrent.atomic.AtomicReferenceArray<ELEMENT> actual)
Create assertion forAtomicReferenceArray
.- Type Parameters:
ELEMENT
- the type of the value contained in theAtomicReferenceArray
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static <FIELD,OBJECT> AtomicReferenceFieldUpdaterAssert<FIELD,OBJECT> assertThat(java.util.concurrent.atomic.AtomicReferenceFieldUpdater<OBJECT,FIELD> actual)
Create assertion forAtomicReferenceFieldUpdater
.- Type Parameters:
FIELD
- the type of the field which gets updated by theAtomicReferenceFieldUpdater
.OBJECT
- the type of the object holding the updatable field.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static <VALUE> AtomicMarkableReferenceAssert<VALUE> assertThat(java.util.concurrent.atomic.AtomicMarkableReference<VALUE> actual)
Create assertion forAtomicMarkableReference
.- Type Parameters:
VALUE
- the type of the value contained in theAtomicMarkableReference
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static <VALUE> AtomicStampedReferenceAssert<VALUE> assertThat(java.util.concurrent.atomic.AtomicStampedReference<VALUE> actual)
Create assertion forAtomicStampedReference
.- Type Parameters:
VALUE
- the type of the value contained in theAtomicStampedReference
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
- Since:
- 2.7.0 / 3.7.0
-
assertThat
public static AbstractThrowableAssert<?,? extends java.lang.Throwable> assertThat(java.lang.Throwable actual)
Creates a new instance of
.ThrowableAssert
- Parameters:
actual
- the actual value.- Returns:
- the created
ThrowableAssert
.
-
assertThatThrownBy
public static AbstractThrowableAssert<?,? extends java.lang.Throwable> assertThatThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Allows to capture and then assert on aThrowable
more easily when used with Java 8 lambdas.Example :
If the provided@Test public void testException() { assertThatThrownBy(() -> { throw new Exception("boom!"); }).isInstanceOf(Exception.class) .hasMessageContaining("boom"); }
ThrowableAssert.ThrowingCallable
does not raise an exception, an error is immediately raised, in that case the test description provided withas(String, Object...)
is not honored. To use a test description, usecatchThrowable(ThrowableAssert.ThrowingCallable)
as shown below.// assertion will fail but "display me" won't appear in the error assertThatThrownBy(() -> { // do nothing }).as("display me").isInstanceOf(Exception.class); // assertion will fail AND "display me" will appear in the error Throwable thrown = catchThrowable(() -> { // do nothing }); assertThat(thrown).as("display me").isInstanceOf(Exception.class);
- Parameters:
shouldRaiseThrowable
- TheThrowableAssert.ThrowingCallable
or lambda with the code that should raise the throwable.- Returns:
- The captured exception or
null
if none was raised by the callable.
-
assertThatCode
public static AbstractThrowableAssert<?,? extends java.lang.Throwable> assertThatCode(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable)
Allows to capture and then assert on aThrowable
more easily when used with Java 8 lambdas.Example :
If the providedThrowingCallable callable = () -> { throw new Exception("boom!"); }; // assertion succeeds assertThatCode(callable).isInstanceOf(Exception.class) .hasMessageContaining("boom"); // assertion fails assertThatCode(callable).doesNotThrowAnyException();
ThrowableAssert.ThrowingCallable
does not validate against next assertions, an error is immediately raised, in that case the test description provided withas(String, Object...)
is not honored. To use a test description, usecatchThrowable(ThrowableAssert.ThrowingCallable)
as shown below.ThrowingCallable doNothing = () -> { // do nothing }; // assertion fails and "display me" appears in the assertion error assertThatCode(doNothing).as("display me") .isInstanceOf(Exception.class); // assertion will fail AND "display me" will appear in the error Throwable thrown = catchThrowable(doNothing); assertThatCode(thrown).as("display me") .isInstanceOf(Exception.class);
This method was not named
assertThat
because the java compiler reported it ambiguous when used directly with a lambda :(- Parameters:
shouldRaiseOrNotThrowable
- TheThrowableAssert.ThrowingCallable
or lambda with the code that should raise the throwable.- Returns:
- The captured exception or
null
if none was raised by the callable. - Since:
- 3.7.0
-
catchThrowable
public static java.lang.Throwable catchThrowable(ThrowableAssert.ThrowingCallable shouldRaiseThrowable)
Allows to catch anThrowable
more easily when used with Java 8 lambdas.This caught
Throwable
can then be asserted.Example:
@Test public void testException() { // when Throwable thrown = catchThrowable(() -> { throw new Exception("boom!"); }); // then assertThat(thrown).isInstanceOf(Exception.class) .hasMessageContaining("boom"); }
- Parameters:
shouldRaiseThrowable
- The lambda with the code that should raise the exception.- Returns:
- The captured exception or
null
if none was raised by the callable.
-
assertThatExceptionOfType
public static <T extends java.lang.Throwable> ThrowableTypeAssert<T> assertThatExceptionOfType(java.lang.Class<? extends T> exceptionType)
Entry point to check that an exception of type T is thrown by a giventhrowingCallable
which allows to chain assertions on the thrown exception.Example:
This method is more or less the same ofassertThatExceptionOfType(IOException.class) .isThrownBy(() -> { throw new IOException("boom!"); }) .withMessage("boom!");
assertThatThrownBy(ThrowableAssert.ThrowingCallable)
but in a more natural way.- Parameters:
exceptionType
- the exception type.- Returns:
- the created
ThrowableTypeAssert
.
-
assertThatNullPointerException
public static ThrowableTypeAssert<java.lang.NullPointerException> assertThatNullPointerException()
Alias forassertThatExceptionOfType(Class)
forNullPointerException
.- Returns:
- the created
ThrowableTypeAssert
. - Since:
- 3.7.0
-
assertThatIllegalArgumentException
public static ThrowableTypeAssert<java.lang.IllegalArgumentException> assertThatIllegalArgumentException()
Alias forassertThatExceptionOfType(Class)
forIllegalArgumentException
.- Returns:
- the created
ThrowableTypeAssert
. - Since:
- 3.7.0
-
assertThatIOException
public static ThrowableTypeAssert<java.io.IOException> assertThatIOException()
Alias forassertThatExceptionOfType(Class)
forIOException
.- Returns:
- the created
ThrowableTypeAssert
. - Since:
- 3.7.0
-
assertThatIllegalStateException
public static ThrowableTypeAssert<java.lang.IllegalStateException> assertThatIllegalStateException()
Alias forassertThatExceptionOfType(Class)
forIllegalStateException
.- Returns:
- the created
ThrowableTypeAssert
. - Since:
- 3.7.0
-
setRemoveAssertJRelatedElementsFromStackTrace
public static void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace)
Sets whether we remove elements related to AssertJ from assertion error stack trace.- Parameters:
removeAssertJRelatedElementsFromStackTrace
- flag.
-
fail
public static void fail(java.lang.String failureMessage)
Throws anAssertionError
with the given message.- Parameters:
failureMessage
- error message.- Throws:
java.lang.AssertionError
- with the given message.
-
fail
public static void fail(java.lang.String failureMessage, java.lang.Object... args)
Throws anAssertionError
with the given message built asString.format(String, Object...)
.- Parameters:
failureMessage
- error message.args
- Arguments referenced by the format specifiers in the format string.- Throws:
java.lang.AssertionError
- with the given built message.
-
fail
public static void fail(java.lang.String failureMessage, java.lang.Throwable realCause)
Throws anAssertionError
with the given message and with theThrowable
that caused the failure.- Parameters:
failureMessage
- the description of the failed assertion. It can benull
.realCause
- cause of the error.- Throws:
java.lang.AssertionError
- with the given message and with theThrowable
that caused the failure.
-
failBecauseExceptionWasNotThrown
public static void failBecauseExceptionWasNotThrown(java.lang.Class<? extends java.lang.Throwable> throwableClass)
Throws anAssertionError
with a message explaining that aThrowable
of given class was expected to be thrown but had not been.shouldHaveThrown(Class)
can be used as a replacement.- Parameters:
throwableClass
- the Throwable class that was expected to be thrown.- Throws:
java.lang.AssertionError
- with a message explaining that aThrowable
of given class was expected to be thrown but had not been.
-
shouldHaveThrown
public static void shouldHaveThrown(java.lang.Class<? extends java.lang.Throwable> throwableClass)
Throws anAssertionError
with a message explaining that aThrowable
of given class was expected to be thrown but had not been.- Parameters:
throwableClass
- the Throwable class that was expected to be thrown.- Throws:
java.lang.AssertionError
- with a message explaining that aThrowable
of given class was expected to be thrown but had not been.
-
setMaxLengthForSingleLineDescription
public static void setMaxLengthForSingleLineDescription(int maxLengthForSingleLineDescription)
In error messages, sets the threshold when iterable/array formatting will on one line (if their String description is less than this parameter) or it will be formatted with one element per line.The following array will be formatted on one line as its length < 80
whereas this array is formatted on multiple lines (one element per line)String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"]
String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards! (Discworld)"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards! (Discworld)"]
- Parameters:
maxLengthForSingleLineDescription
- the maximum length for an iterable/array to be displayed on one line
-
setMaxElementsForPrinting
public static void setMaxElementsForPrinting(int maxElementsForPrinting)
In error messages, sets the threshold for how many elements from one iterable/array/map will be included in the in the description. E.q. When this method is called with a value of3
.The following array will be formatted entirely as it's length is <= 3:
whereas this array is formatted only with it's first 3 elements, followed byString[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice"]
...
:String[] greatBooks = array("A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", "Guards! Guards!"); // formatted as: ["A Game of Thrones", "The Lord of the Rings", "Assassin's Apprentice", ...]
- Parameters:
maxElementsForPrinting
- the maximum elements that would be printed from one iterable/array/map- Since:
- 2.6.0 / 3.6.0
-
extractProperty
public static <T> Properties<T> extractProperty(java.lang.String propertyName, java.lang.Class<T> propertyType)
Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).Typical usage is to chain
extractProperty
withfrom
method, see examples below :// extract simple property values having a java standard type (here String) assertThat(extractProperty("name", String.class).from(fellowshipOfTheRing)) .contains("Boromir", "Gandalf", "Frodo", "Legolas") .doesNotContain("Sauron", "Elrond"); // extracting property works also with user's types (here Race) assertThat(extractProperty("race", String.class).from(fellowshipOfTheRing)) .contains(HOBBIT, ELF).doesNotContain(ORC); // extract nested property on Race assertThat(extractProperty("race.name", String.class).from(fellowshipOfTheRing)) .contains("Hobbit", "Elf") .doesNotContain("Orc");
-
extractProperty
public static Properties<java.lang.Object> extractProperty(java.lang.String propertyName)
Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).Typical usage is to chain
extractProperty
withfrom
method, see examples below :// extract simple property values, as no type has been defined the extracted property will be considered as Object // to define the real property type (here String) use extractProperty("name", String.class) instead. assertThat(extractProperty("name").from(fellowshipOfTheRing)) .contains("Boromir", "Gandalf", "Frodo", "Legolas") .doesNotContain("Sauron", "Elrond"); // extracting property works also with user's types (here Race), even though it will be considered as Object // to define the real property type (here String) use extractProperty("name", Race.class) instead. assertThat(extractProperty("race").from(fellowshipOfTheRing)).contains(HOBBIT, ELF).doesNotContain(ORC); // extract nested property on Race assertThat(extractProperty("race.name").from(fellowshipOfTheRing)).contains("Hobbit", "Elf").doesNotContain("Orc");
-
tuple
public static Tuple tuple(java.lang.Object... values)
Utility method to build nicely aTuple
when working withAbstractIterableAssert.extracting(String...)
orAbstractObjectArrayAssert.extracting(String...)
-
setAllowExtractingPrivateFields
public static void setAllowExtractingPrivateFields(boolean allowExtractingPrivateFields)
Globally sets whether
andIterableAssert#extracting(String)
should be allowed to extract private fields, if not and they try it fails with exception.ObjectArrayAssert#extracting(String)
- Parameters:
allowExtractingPrivateFields
- allow private fields extraction. Defaulttrue
.
-
setAllowComparingPrivateFields
public static void setAllowComparingPrivateFields(boolean allowComparingPrivateFields)
Globally sets whether the use of private fields is allowed for comparison. The following (incomplete) list of methods will be impacted by this change :-
AbstractIterableAssert.usingElementComparatorOnFields(java.lang.String...)
AbstractObjectAssert.isEqualToComparingFieldByField(Object)
false
and these methods try to compare private fields, it will fail with an exception.- Parameters:
allowComparingPrivateFields
- allow private fields comparison. Defaulttrue
.
-
-
entry
public static <K,V> MapEntry<K,V> entry(K key, V value)
Only delegate toMapEntry.entry(Object, Object)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useMapEntry
if you prefer).Typical usage is to call
entry
in MapAssertcontains
assertion, see examples below :Map
ringBearers = ... // init omitted assertThat(ringBearers).contains(entry(oneRing, frodo), entry(nenya, galadriel));
-
atIndex
public static Index atIndex(int index)
Only delegate toIndex.atIndex(int)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useIndex
if you prefer).Typical usage :
List<Ring> elvesRings = newArrayList(vilya, nenya, narya); assertThat(elvesRings).contains(vilya, atIndex(0)).contains(nenya, atIndex(1)).contains(narya, atIndex(2));
-
offset
public static Offset<java.lang.Double> offset(java.lang.Double value)
Assertions entry point for doubleOffset
.Typical usage :
assertThat(8.1).isEqualTo(8.0, offset(0.1));
-
offset
public static Offset<java.lang.Float> offset(java.lang.Float value)
Assertions entry point for floatOffset
.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, offset(0.2f));
-
within
public static Offset<java.lang.Double> within(java.lang.Double value)
Alias foroffset(Double)
to use with isCloseTo assertions.Typical usage :
assertThat(8.1).isCloseTo(8.0, within(0.1));
-
withPrecision
public static Offset<java.lang.Double> withPrecision(java.lang.Double value)
Alias foroffset(Double)
to use with real number assertions.Typical usage :
assertThat(8.1).isEqualTo(8.0, withPrecision(0.1));
-
within
public static Offset<java.lang.Float> within(java.lang.Float value)
Alias foroffset(Float)
to use with isCloseTo assertions.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, within(0.2f));
-
withPrecision
public static Offset<java.lang.Float> withPrecision(java.lang.Float value)
Alias foroffset(Float)
to use with real number assertions.Typical usage :
assertThat(8.2f).isEqualTo(8.0f, withPrecision(0.2f));
-
within
public static Offset<java.math.BigDecimal> within(java.math.BigDecimal value)
Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.Typical usage :
assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), within(BigDecimal.ONE));
-
within
public static Offset<java.math.BigInteger> within(java.math.BigInteger value)
Assertions entry point for BigIntegerOffset
to use with isCloseTo assertions.Typical usage :
assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), within(new BigInteger("2")));
- Since:
- 2.7.0 / 3.7.0
-
within
public static Offset<java.lang.Byte> within(java.lang.Byte value)
Assertions entry point for ByteOffset
to use with isCloseTo assertions.Typical usage :
assertThat((byte)10).isCloseTo((byte)11, within((byte)1));
-
within
public static Offset<java.lang.Integer> within(java.lang.Integer value)
Assertions entry point for IntegerOffset
to use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, within(1));
-
within
public static Offset<java.lang.Short> within(java.lang.Short value)
Assertions entry point for ShortOffset
to use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, within(1));
-
within
public static Offset<java.lang.Long> within(java.lang.Long value)
Assertions entry point for LongOffset
to use with isCloseTo assertions.Typical usage :
assertThat(5l).isCloseTo(7l, within(2l));
-
within
public static TemporalUnitOffset within(long value, java.time.temporal.TemporalUnit unit)
Assertions entry point forTemporalUnitOffset
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));
- Since:
- 3.7.0
-
withinPercentage
public static Percentage withinPercentage(java.lang.Double value)
Assertions entry point for DoublePercentage
to use with isCloseTo assertions for percentages.Typical usage :
assertThat(11.0).isCloseTo(10.0, withinPercentage(10.0));
-
withinPercentage
public static Percentage withinPercentage(java.lang.Integer value)
Assertions entry point for IntegerPercentage
to use with isCloseTo assertions for percentages.Typical usage :
assertThat(11).isCloseTo(10, withinPercentage(10));
-
withinPercentage
public static Percentage withinPercentage(java.lang.Long value)
Assertions entry point for LongPercentage
to use with isCloseTo assertions for percentages.Typical usage :
assertThat(11L).isCloseTo(10L, withinPercentage(10L));
-
byLessThan
public static Offset<java.lang.Double> byLessThan(java.lang.Double value)
Alias foroffset(Double)
to use with isCloseTo assertions.Typical usage :
assertThat(8.1).isCloseTo(8.0, byLessThan(0.1));
-
byLessThan
public static Offset<java.lang.Float> byLessThan(java.lang.Float value)
Alias foroffset(Float)
to use with isCloseTo assertions.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, byLessThan(0.2f));
-
byLessThan
public static Offset<java.math.BigDecimal> byLessThan(java.math.BigDecimal value)
Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.Typical usage :
assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), byLessThan(BigDecimal.ONE));
-
byLessThan
public static Offset<java.math.BigInteger> byLessThan(java.math.BigInteger value)
Assertions entry point for BigIntegerOffset
to use with isCloseTo assertions.Typical usage :
assertThat(BigInteger.TEN).isCloseTo(new BigInteger("11"), byLessThan(new BigInteger("2")));
- Since:
- 2.7.0 / 3.7.0
-
byLessThan
public static Offset<java.lang.Byte> byLessThan(java.lang.Byte value)
Assertions entry point for ByteOffset
to use with isCloseTo assertions.Typical usage :
assertThat((byte)10).isCloseTo((byte)11, byLessThan((byte)1));
-
byLessThan
public static Offset<java.lang.Integer> byLessThan(java.lang.Integer value)
Assertions entry point for IntegerOffset
to use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, byLessThan(1));
-
byLessThan
public static Offset<java.lang.Short> byLessThan(java.lang.Short value)
Assertions entry point for ShortOffset
to use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, byLessThan(1));
-
byLessThan
public static Offset<java.lang.Long> byLessThan(java.lang.Long value)
Assertions entry point for LongOffset
to use with isCloseTo assertions.Typical usage :
assertThat(5l).isCloseTo(7l, byLessThan(2l));
-
byLessThan
public static TemporalUnitOffset byLessThan(long value, java.time.temporal.TemporalUnit unit)
Assertions entry point forTemporalUnitOffset
with strict less than condition to use withisCloseTo
temporal assertions.Typical usage :
LocalTime _07_10 = LocalTime.of(7, 10); LocalTime _07_12 = LocalTime.of(7, 12); assertThat(_07_10).isCloseTo(_07_12, byLessThan(5, ChronoUnit.MINUTES));
- Since:
- 3.7.0
-
from
public static <F,T> java.util.function.Function<F,T> from(java.util.function.Function<F,T> extractor)
A syntax sugar to write fluent assertion usingAbstractObjectAssert.returns(Object, Function)
.Example:
Jedi yoda = new Jedi("Yoda", "Green"); assertThat(yoda).returns("Yoda", from(Jedi::getName)) .returns(2.4, from(Jedi::getHeight)) .returns(150, from(Jedi::getWeight));
- Type Parameters:
F
- Type of test subjectT
- Type of the property under the assertion- Parameters:
extractor
- A function to extract test subject's property- Returns:
- same instance of
extractor
-
allOf
@SafeVarargs public static <T> Condition<T> allOf(Condition<? super T>... conditions)
Creates a newAllOf
- Type Parameters:
T
- the type of object the given condition accept.- Parameters:
conditions
- the conditions to evaluate.- Returns:
- the created
AnyOf
. - Throws:
java.lang.NullPointerException
- if the given array isnull
.java.lang.NullPointerException
- if any of the elements in the given array isnull
.
-
allOf
public static <T> Condition<T> allOf(java.lang.Iterable<? extends Condition<? super T>> conditions)
Creates a newAllOf
- Type Parameters:
T
- the type of object the given condition accept.- Parameters:
conditions
- the conditions to evaluate.- Returns:
- the created
AnyOf
. - Throws:
java.lang.NullPointerException
- if the given iterable isnull
.java.lang.NullPointerException
- if any of the elements in the given iterable isnull
.
-
anyOf
@SafeVarargs public static <T> Condition<T> anyOf(Condition<? super T>... conditions)
Only delegate toAnyOf.anyOf(Condition...)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useAnyOf
if you prefer).Typical usage (
jedi
andsith
areCondition
) :assertThat("Vader").is(anyOf(jedi, sith));
-
anyOf
public static <T> Condition<T> anyOf(java.lang.Iterable<? extends Condition<? super T>> conditions)
Creates a newAnyOf
- Type Parameters:
T
- the type of object the given condition accept.- Parameters:
conditions
- the conditions to evaluate.- Returns:
- the created
AnyOf
. - Throws:
java.lang.NullPointerException
- if the given iterable isnull
.java.lang.NullPointerException
- if any of the elements in the given iterable isnull
.
-
doesNotHave
public static <T> DoesNotHave<T> doesNotHave(Condition<? super T> condition)
Creates a newDoesNotHave
.- Parameters:
condition
- the condition to inverse.- Returns:
- The Not condition created.
-
not
public static <T> Not<T> not(Condition<? super T> condition)
Creates a newNot
.- Parameters:
condition
- the condition to inverse.- Returns:
- The Not condition created.
-
filter
public static <E> Filters<E> filter(E[] array)
Only delegate toFilters.filter(Object[])
so that Assertions offers a full feature entry point to all AssertJ features (but you can useFilters
if you prefer).Note that the given array is not modified, the filters are performed on an
Iterable
copy of the array.Typical usage with
Condition
:assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);
and with filter language based on java bean property :
assertThat(filter(players).with("pointsPerGame").greaterThan(20).and("assistsPerGame").greaterThan(7).get()) .containsOnly(james, rose);
-
filter
public static <E> Filters<E> filter(java.lang.Iterable<E> iterableToFilter)
Only delegate toFilters.filter(Object[])
so that Assertions offers a full feature entry point to all AssertJ features (but you can useFilters
if you prefer).Note that the given
Iterable
is not modified, the filters are performed on a copy.Typical usage with
Condition
:assertThat(filter(players).being(potentialMVP).get()).containsOnly(james, rose);
and with filter language based on java bean property :
assertThat(filter(players).with("pointsPerGame").greaterThan(20).and("assistsPerGame").greaterThan(7).get()) .containsOnly(james, rose);
-
in
public static InFilter in(java.lang.Object... values)
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches one of the given values.As often, an example helps:
Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); Employee noname = new Employee(4L, null, 50); List<Employee> employees = newArrayList(yoda, luke, obiwan, noname); assertThat(employees).filteredOn("age", in(800, 26)) .containsOnly(yoda, obiwan, luke);
- Parameters:
values
- values to match (one match is sufficient)- Returns:
- the created "in" filter
-
notIn
public static NotInFilter notIn(java.lang.Object... valuesNotToMatch)
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches does not match any of the given values.As often, an example helps:
Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); Employee noname = new Employee(4L, null, 50); List<Employee> employees = newArrayList(yoda, luke, obiwan, noname); assertThat(employees).filteredOn("age", notIn(800, 50)) .containsOnly(luke);
- Parameters:
valuesNotToMatch
- values not to match (none of the values must match)- Returns:
- the created "not in" filter
-
not
public static NotFilter not(java.lang.Object valueNotToMatch)
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches does not match the given value.As often, an example helps:
Employee yoda = new Employee(1L, new Name("Yoda"), 800); Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); Employee noname = new Employee(4L, null, 50); List<Employee> employees = newArrayList(yoda, luke, obiwan, noname); assertThat(employees).filteredOn("age", not(800)) .containsOnly(luke, noname);
- Parameters:
valueNotToMatch
- the value not to match- Returns:
- the created "not" filter
-
contentOf
public static java.lang.String contentOf(java.io.File file, java.nio.charset.Charset charset)
Loads the text content of a file, so that it can be passed toassertThat(String)
.Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
assertThat(File)
.- Parameters:
file
- the file.charset
- the character set to use.- Returns:
- the content of the file.
- Throws:
java.lang.NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
public static java.lang.String contentOf(java.io.File file, java.lang.String charsetName)
Loads the text content of a file, so that it can be passed toassertThat(String)
.Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
assertThat(File)
.- Parameters:
file
- the file.charsetName
- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
java.lang.IllegalArgumentException
- if the given character set is not supported on this platform.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
public static java.lang.String contentOf(java.io.File file)
Loads the text content of a file with the default character set, so that it can be passed toassertThat(String)
.Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
assertThat(File)
.- Parameters:
file
- the file.- Returns:
- the content of the file.
- Throws:
RuntimeIOException
- if an I/O exception occurs.
-
linesOf
public static java.util.List<java.lang.String> linesOf(java.io.File file)
Loads the text content of a file into a list of strings with the default charset, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file
- the file.- Returns:
- the content of the file.
- Throws:
java.lang.NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
linesOf
public static java.util.List<java.lang.String> linesOf(java.io.File file, java.nio.charset.Charset charset)
Loads the text content of a file into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file
- the file.charset
- the character set to use.- Returns:
- the content of the file.
- Throws:
java.lang.NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
linesOf
public static java.util.List<java.lang.String> linesOf(java.io.File file, java.lang.String charsetName)
Loads the text content of a file into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file
- the file.charsetName
- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
java.lang.NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
public static java.lang.String contentOf(java.net.URL url, java.nio.charset.Charset charset)
Loads the text content of a URL, so that it can be passed toassertThat(String)
.Note that this will load the entire contents in memory.
- Parameters:
url
- the URL.charset
- the character set to use.- Returns:
- the content of the URL.
- Throws:
java.lang.NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
public static java.lang.String contentOf(java.net.URL url, java.lang.String charsetName)
Loads the text content of a URL, so that it can be passed toassertThat(String)
.Note that this will load the entire contents in memory.
- Parameters:
url
- the URL.charsetName
- the name of the character set to use.- Returns:
- the content of the URL.
- Throws:
java.lang.IllegalArgumentException
- if the given character set is not supported on this platform.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
public static java.lang.String contentOf(java.net.URL url)
Loads the text content of a URL with the default character set, so that it can be passed toassertThat(String)
.Note that this will load the entire file in memory; for larger files.
- Parameters:
url
- the URL.- Returns:
- the content of the file.
- Throws:
RuntimeIOException
- if an I/O exception occurs.
-
linesOf
public static java.util.List<java.lang.String> linesOf(java.net.URL url)
Loads the text content of a URL into a list of strings with the default charset, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url
- the URL.- Returns:
- the content of the file.
- Throws:
java.lang.NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
linesOf
public static java.util.List<java.lang.String> linesOf(java.net.URL url, java.nio.charset.Charset charset)
Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url
- the URL.charset
- the character set to use.- Returns:
- the content of the file.
- Throws:
java.lang.NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
linesOf
public static java.util.List<java.lang.String> linesOf(java.net.URL url, java.lang.String charsetName)
Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url
- the URL.charsetName
- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
java.lang.NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
setLenientDateParsing
public static void setLenientDateParsing(boolean value)
Instead of using default strict date/time parsing, it is possible to use lenient parsing mode for default date formats parser to interpret inputs that do not precisely match supported date formats (lenient parsing).With strict parsing, inputs must match exactly date/time format.
Example:
To revert to default strict date parsing, callfinal Date date = Dates.parse("2001-02-03"); final Date dateTime = parseDatetime("2001-02-03T04:05:06"); final Date dateTimeWithMs = parseDatetimeWithMs("2001-02-03T04:05:06.700"); Assertions.setLenientDateParsing(true); // assertions will pass assertThat(date).isEqualTo("2001-01-34"); assertThat(date).isEqualTo("2001-02-02T24:00:00"); assertThat(date).isEqualTo("2001-02-04T-24:00:00.000"); assertThat(dateTime).isEqualTo("2001-02-03T04:05:05.1000"); assertThat(dateTime).isEqualTo("2001-02-03T04:04:66"); assertThat(dateTimeWithMs).isEqualTo("2001-02-03T04:05:07.-300"); // assertions will fail assertThat(date).hasSameTimeAs("2001-02-04"); // different date assertThat(dateTime).hasSameTimeAs("2001-02-03 04:05:06"); // leniency does not help here
setLenientDateParsing(false)
.- Parameters:
value
- whether lenient parsing mode should be enabled or not
-
registerCustomDateFormat
public static void registerCustomDateFormat(java.text.DateFormat userCustomDateFormat)
Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String)
.User date formats are used before default ones in the order they have been registered (first registered, first used).
AssertJ is gonna use any date formats registered with one of these methods :
AbstractDateAssert.withDateFormat(String)
AbstractDateAssert.withDateFormat(java.text.DateFormat)
registerCustomDateFormat(java.text.DateFormat)
registerCustomDateFormat(String)
Beware that AssertJ will use the newly registered format for all remaining Date assertions in the test suite
To revert to default formats only, call
useDefaultDateFormatsOnly()
orAbstractDateAssert.withDefaultDateFormatsOnly()
.Code examples:
Date date = ... // set to 2003 April the 26th assertThat(date).isEqualTo("2003-04-26"); try { // date with a custom format : failure since the default formats don't match. assertThat(date).isEqualTo("2003/04/26"); } catch (AssertionError e) { assertThat(e).hasMessage("Failed to parse 2003/04/26 with any of these date formats: " + "[yyyy-MM-dd'T'HH:mm:ss.SSS, yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]"); } // registering a custom date format to make the assertion pass registerCustomDateFormat(new SimpleDateFormat("yyyy/MM/dd")); // registerCustomDateFormat("yyyy/MM/dd") would work to. assertThat(date).isEqualTo("2003/04/26"); // the default formats are still available and should work assertThat(date).isEqualTo("2003-04-26");
- Parameters:
userCustomDateFormat
- the new Date format used for String based Date assertions.
-
registerCustomDateFormat
public static void registerCustomDateFormat(java.lang.String userCustomDateFormatPattern)
Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String)
.User date formats are used before default ones in the order they have been registered (first registered, first used).
AssertJ is gonna use any date formats registered with one of these methods :
AbstractDateAssert.withDateFormat(String)
AbstractDateAssert.withDateFormat(java.text.DateFormat)
registerCustomDateFormat(java.text.DateFormat)
registerCustomDateFormat(String)
Beware that AssertJ will use the newly registered format for all remaining Date assertions in the test suite.
To revert to default formats only, call
useDefaultDateFormatsOnly()
orAbstractDateAssert.withDefaultDateFormatsOnly()
.Code examples:
Date date = ... // set to 2003 April the 26th assertThat(date).isEqualTo("2003-04-26"); try { // date with a custom format : failure since the default formats don't match. assertThat(date).isEqualTo("2003/04/26"); } catch (AssertionError e) { assertThat(e).hasMessage("Failed to parse 2003/04/26 with any of these date formats: " + "[yyyy-MM-dd'T'HH:mm:ss.SSS, yyyy-MM-dd'T'HH:mm:ss, yyyy-MM-dd]"); } // registering a custom date format to make the assertion pass registerCustomDateFormat("yyyy/MM/dd"); assertThat(date).isEqualTo("2003/04/26"); // the default formats are still available and should work assertThat(date).isEqualTo("2003-04-26");
- Parameters:
userCustomDateFormatPattern
- the new Date format pattern used for String based Date assertions.
-
useDefaultDateFormatsOnly
public static void useDefaultDateFormatsOnly()
Remove all registered custom date formats => use only the defaults date formats to parse string as date.Beware that the default formats are expressed in the current local timezone.
Defaults date format are:
yyyy-MM-dd'T'HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss.SSS
(forTimestamp
String representation support)yyyy-MM-dd'T'HH:mm:ss
yyyy-MM-dd
Example of valid string date representations:
2003-04-26T03:01:02.999
2003-04-26 03:01:02.999
2003-04-26T13:01:02
2003-04-26
-
assertThat
public static <T> T assertThat(AssertProvider<T> component)
Delegates the creation of theAssert
to theAssertProvider.assertThat()
of the given component.Read the comments on
AssertProvider
for an example of its usage.- Parameters:
component
- the component that creates its own assert- Returns:
- the associated
Assert
of the given component
-
assertThat
public static AbstractCharSequenceAssert<?,? extends java.lang.CharSequence> assertThat(java.lang.CharSequence actual)
Creates a new instance of
.CharSequenceAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <ELEMENT> IterableAssert<ELEMENT> assertThat(java.lang.Iterable<? extends ELEMENT> actual)
Creates a new instance of
.IterableAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <ELEMENT> IterableAssert<ELEMENT> assertThat(java.util.Iterator<? extends ELEMENT> actual)
Creates a new instance of
.IterableAssert
Be aware that calls to most methods on returned IterableAssert will consume Iterator so it won't be possible to iterate over it again. Calling multiple methods on returned IterableAssert is safe as Iterator's elements are cached by IterableAssert first time Iterator is consumed.
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <ELEMENT> ListAssert<ELEMENT> assertThat(java.util.List<? extends ELEMENT> actual)
Creates a new instance of
.ListAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <ELEMENT,STREAM extends java.util.stream.BaseStream<ELEMENT,STREAM>> AbstractListAssert<?,java.util.List<? extends ELEMENT>,ELEMENT,ObjectAssert<ELEMENT>> assertThat(java.util.stream.BaseStream<? extends ELEMENT,STREAM> actual)
Creates a new instance of
from the givenListAssert
BaseStream
.Be aware that to create the returned
ListAssert
the given theBaseStream
is consumed so it won't be possible to use it again. Calling multiple methods on the returnedListAssert
is safe as it only interacts with theList
built from theBaseStream
.This method accepts
Stream
and primitive stream variantsIntStream
,LongStream
andDoubleStream
.- Parameters:
actual
- the actualBaseStream
value.- Returns:
- the created assertion object.
-
assertThat
public static AbstractPathAssert<?> assertThat(java.nio.file.Path actual)
Creates a new instance ofPathAssert
- Parameters:
actual
- the path to test- Returns:
- the created assertion object
-
assertThat
public static <K,V> MapAssert<K,V> assertThat(java.util.Map<K,V> actual)
Creates a new instance of
.MapAssert
Returned type is
MapAssert
as it overrides method to annotate them withSafeVarargs
avoiding annoying warnings.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <T extends java.lang.Comparable<? super T>> AbstractComparableAssert<?,T> assertThat(T actual)
Creates a new instance of
with standard comparison semantics.GenericComparableAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
public static <T extends AssertDelegateTarget> T assertThat(T assertion)
Returns the given assertion. This method improves code readability by surrounding the given assertion withassertThat
.Consider for example the following MyButton and MyButtonAssert classes:
As MyButtonAssert implements AssertDelegateTarget, you can usepublic class MyButton extends JButton { private boolean blinking; public boolean isBlinking() { return this.blinking; } public void setBlinking(boolean blink) { this.blinking = blink; } } private static class MyButtonAssert implements AssertDelegateTarget { private MyButton button; MyButtonAssert(MyButton button) { this.button = button; } void isBlinking() { // standard assertion from core Assertions.assertThat assertThat(button.isBlinking()).isTrue(); } void isNotBlinking() { // standard assertion from core Assertions.assertThat assertThat(button.isBlinking()).isFalse(); } }
assertThat(buttonAssert).isBlinking();
instead ofbuttonAssert.isBlinking();
to have easier to read assertions:@Test public void AssertDelegateTarget_example() { MyButton button = new MyButton(); MyButtonAssert buttonAssert = new MyButtonAssert(button); // you can encapsulate MyButtonAssert assertions methods within assertThat assertThat(buttonAssert).isNotBlinking(); // same as : buttonAssert.isNotBlinking(); button.setBlinking(true); assertThat(buttonAssert).isBlinking(); // same as : buttonAssert.isBlinking(); }
- Type Parameters:
T
- the generic type of the user-defined assert.- Parameters:
assertion
- the assertion to return.- Returns:
- the given assertion.
-
useRepresentation
public static void useRepresentation(Representation customRepresentation)
Register aRepresentation
that will be used in all following assertions.Representation
are used to format types in assertions error messages.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$>
- Since:
- 2.5.0 / 3.5.0
-
registerFormatterForType
public static <T> void registerFormatterForType(java.lang.Class<T> type, java.util.function.Function<T,java.lang.String> formatter)
Assertions error messages uses aRepresentation
to format the different types involved, using this method you can control the formatting of a given type by providing a specific formatter.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);
- Parameters:
type
-formatter
-- Since:
- 3.5.0
-
useDefaultRepresentation
public static void useDefaultRepresentation()
Fallback to useStandardRepresentation
to revert the effect of callinguseRepresentation(Representation)
.- Since:
- 2.5.0 / 3.5.0
-
-