Class AssertionsForClassTypes
- Direct Known Subclasses:
AssertionsForInterfaceTypes
assertThat
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 proper assertThat
method (normally assertThat(Throwable)
as foo might implement an interface like List,
if that occurred assertThat(List)
would also be a possible choice - thus confusing java 8.
This why Assertions
have been split in AssertionsForClassTypes
and AssertionsForInterfaceTypes
(see http://stackoverflow.com/questions/29499847/ambiguous-method-in-java-8-why).
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Condition
<T> Creates a newAllOf
static <T> Condition
<T> Creates a newAllOf
static <T> Condition
<T> Creates a newAnyOf
static <T> Condition
<T> Only delegate toAnyOf.anyOf(Condition...)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useAnyOf
if you prefer).static 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 AbstractFileAssert
<?> assertThat
(File actual) Creates a new instance of
.FileAssert
static AbstractInputStreamAssert
<?, ? extends InputStream> assertThat
(InputStream actual) Creates a new instance of
.InputStreamAssert
static AbstractBooleanAssert
<?> assertThat
(Boolean actual) Creates a new instance of
.BooleanAssert
static AbstractByteAssert
<?> assertThat
(Byte actual) Creates a new instance of
.ByteAssert
static AbstractCharacterAssert
<?> assertThat
(Character actual) Creates a new instance of
.CharacterAssert
static AbstractClassAssert
<?> assertThat
(Class<?> actual) Creates a new instance ofClassAssert
static AbstractDoubleAssert
<?> assertThat
(Double actual) Creates a new instance of
.DoubleAssert
static AbstractFloatAssert
<?> assertThat
(Float actual) Creates a new instance of
.FloatAssert
static AbstractIntegerAssert
<?> assertThat
(Integer actual) Creates a new instance of
.IntegerAssert
static AbstractLongAssert
<?> assertThat
(Long actual) Creates a new instance of
.LongAssert
static AbstractShortAssert
<?> assertThat
(Short actual) Creates a new instance of
.ShortAssert
static AbstractCharSequenceAssert
<?, String> assertThat
(String actual) Creates a new instance of
.StringAssert
static AbstractThrowableAssert
<?, ? extends Throwable> assertThat
(Throwable actual) Creates a new instance of
.ThrowableAssert
static AbstractBigDecimalAssert
<?> assertThat
(BigDecimal actual) Creates a new instance of
.BigDecimalAssert
static AbstractUriAssert
<?> assertThat
(URI actual) Creates a new instance of
.UriAssert
static AbstractUrlAssert
<?> assertThat
(URL actual) Creates a new instance of
.UrlAssert
static AbstractInstantAssert
<?> assertThat
(Instant instant) Creates a new instance of
.InstantAssert
static AbstractLocalDateAssert
<?> assertThat
(LocalDate localDate) Creates a new instance of
.LocalDateAssert
static AbstractLocalDateTimeAssert
<?> assertThat
(LocalDateTime actual) Creates a new instance of
.LocalDateTimeAssert
static AbstractLocalTimeAssert
<?> assertThat
(LocalTime actual) Creates a new instance of
.LocalTimeAssert
static AbstractOffsetDateTimeAssert
<?> assertThat
(OffsetDateTime actual) Creates a new instance of
.OffsetDateTime
static AbstractOffsetTimeAssert
<?> assertThat
(OffsetTime actual) Create assertion forOffsetTime
.static AbstractZonedDateTimeAssert
<?> assertThat
(ZonedDateTime actual) Creates a new instance of
.ZonedDateTimeAssert
static <RESULT> CompletableFutureAssert
<RESULT> assertThat
(CompletableFuture<RESULT> actual) Create assertion forCompletableFuture
.static AbstractDateAssert
<?> assertThat
(Date actual) Creates a new instance of
.DateAssert
static <VALUE> OptionalAssert
<VALUE> assertThat
(Optional<VALUE> actual) Create assertion forOptional
.static OptionalDoubleAssert
assertThat
(OptionalDouble actual) Create assertion forOptionalDouble
.static OptionalIntAssert
assertThat
(OptionalInt actual) Create assertion forOptionalInt
.static OptionalLongAssert
assertThat
(OptionalLong actual) Create assertion forOptionalInt
.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 Throwable> assertThatCode
(ThrowableAssert.ThrowingCallable shouldRaiseOrNotThrowable) Allows to capture and then assert on aThrowable
more easily when used with Java 8 lambdas.static <T extends Throwable>
ThrowableTypeAssert<T> assertThatExceptionOfType
(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 AbstractThrowableAssert
<?, ? extends Throwable> assertThatThrownBy
(ThrowableAssert.ThrowingCallable shouldRaiseThrowable) Allows to capture and then assert on aThrowable
.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 Throwable
catchThrowable
(ThrowableAssert.ThrowingCallable shouldRaiseThrowable) Allows to catch anThrowable
more easily when used with Java 8 lambdas.static String
Loads the text content of a file with the default character set, so that it can be passed toassertThat(String)
.static String
Loads the text content of a file, so that it can be passed toassertThat(String)
.static String
Loads the text content of a file, so that it can be passed toassertThat(String)
.static String
Loads the text content of a URL with the default character set, so that it can be passed toassertThat(String)
.static String
Loads the text content of a URL, so that it can be passed toassertThat(String)
.static String
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
<Object> extractProperty
(String propertyName) Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).static <T> Properties
<T> extractProperty
(String propertyName, Class<T> propertyType) Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).static void
Only delegate toFail.fail(String)
so that Assertions offers a full feature entry point to all Assertj Assert features (but you can use Fail if you prefer).static void
Only delegate toFail.fail(String, Throwable)
so that Assertions offers a full feature entry point to all AssertJ features (but you can use Fail if you prefer).static void
failBecauseExceptionWasNotThrown
(Class<? extends Throwable> exceptionClass) Only delegate toFail.failBecauseExceptionWasNotThrown(Class)
so that Assertions offers a full feature entry point to all AssertJ features (but you can use Fail if you prefer).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> 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 InFilter
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches one of the given values.Loads the text content of a file into a list of strings with the default charset, each string corresponding to a line.Loads the text content of a file into a list of strings, each string corresponding to a line.Loads the text content of a file into a list of strings, each string corresponding to a line.Loads the text content of a URL into a list of strings with the default charset, each string corresponding to a line.Loads the text content of a URL into a list of strings, each string corresponding to a line.Loads the text content of a URL into a list of strings, each string corresponding to a line.static NotFilter
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches does not match the given value.static <T> Not
<T> Creates a newNot
.static NotInFilter
Create aFilterOperator
to use infilteredOn(String, FilterOperation)
to express a filter keeping all Iterable elements whose property/field value matches does not match any of the given values.Assertions entry point for doubleOffset
.Assertions entry point for floatOffset
.static void
registerCustomDateFormat
(String userCustomDateFormatPattern) Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String)
.static void
registerCustomDateFormat
(DateFormat userCustomDateFormat) Add the given date format to the ones used to parse date String in String based Date assertions likeAbstractDateAssert.isEqualTo(String)
.static 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
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) Only delegate toFail.setRemoveAssertJRelatedElementsFromStackTrace(boolean)
so that Assertions offers a full feature entry point to all AssertJ Assert features (but you can useFail
if you prefer).static void
shouldHaveThrown
(Class<? extends Throwable> exceptionClass) Only delegate toFail.shouldHaveThrown(Class)
so that Assertions offers a full feature entry point to all AssertJ features (but you can use Fail if you prefer).static Tuple
Utility method to build nicely aTuple
when working withAbstractIterableAssert.extracting(String...)
orAbstractObjectArrayAssert.extracting(String...)
static void
Remove all registered custom date formats => use only the defaults date formats to parse string as date.Assertions entry point for ByteOffset
to use with isCloseTo assertions.Alias foroffset(Double)
to use with isCloseTo assertions.Alias foroffset(Float)
to use with isCloseTo assertions.Assertions entry point for IntegerOffset
to use with isCloseTo assertions.Assertions entry point for LongOffset
to use with isCloseTo assertions.Assertions entry point for ShortOffset
to use with isCloseTo assertions.static Offset
<BigDecimal> within
(BigDecimal value) Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.static Percentage
withinPercentage
(Double value) Assertions entry point for DoublePercentage
to use with isCloseTo assertions for percentages.static Percentage
withinPercentage
(Integer value) Assertions entry point for IntegerPercentage
to use with isCloseTo assertions for percentages.static Percentage
withinPercentage
(Long value) Assertions entry point for LongPercentage
to use with isCloseTo assertions for percentages.
-
Constructor Details
-
AssertionsForClassTypes
protected AssertionsForClassTypes()Creates a newAssertionsForClassTypes
.
-
-
Method Details
-
assertThat
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
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
Create assertion forOptionalDouble
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Create assertion forOptionalInt
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Create assertion forOptionalInt
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.BigDecimalAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.UriAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.UrlAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.BooleanAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.BooleanAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.BooleanArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ByteAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ByteAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ByteArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.CharacterAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.CharArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.CharacterAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance ofClassAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.DoubleAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.DoubleAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.DoubleArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.FileAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.InputStreamAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.FloatAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.FloatAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.FloatArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.IntegerAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.IntArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.IntegerAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.LongAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.LongAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.LongArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ObjectAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ObjectArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ShortAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ShortAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ShortArrayAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.StringAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.DateAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.ZonedDateTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.LocalDateTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.OffsetDateTime
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Create assertion forOffsetTime
.- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.LocalTimeAssert
- Parameters:
actual
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.LocalDateAssert
- Parameters:
localDate
- the actual value.- Returns:
- the created assertion object.
-
assertThat
Creates a new instance of
.InstantAssert
- Parameters:
instant
- the actual value.- Returns:
- the created assertion object.
- Since:
- 3.7.0
-
assertThat
Creates a new instance of
.ThrowableAssert
- Parameters:
actual
- the actual value.- Returns:
- the created
ThrowableAssert
.
-
assertThatThrownBy
public static AbstractThrowableAssert<?,? extends Throwable> assertThatThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable) Allows to capture and then assert on aThrowable
.Example :
Another (probably more natural) way of checking that some code throws an exception is@Test public void testException() { assertThatThrownBy(() -> { throw new Exception("boom!"); }).isInstanceOf(Exception.class) .hasMessageContaining("boom"); }
assertThatExceptionOfType(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.
-
assertThatExceptionOfType
public static <T extends Throwable> ThrowableTypeAssert<T> assertThatExceptionOfType(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 actual value.- Returns:
- the created
ThrowableTypeAssert
.
-
assertThatCode
public static AbstractThrowableAssert<?,? extends 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
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.
-
setRemoveAssertJRelatedElementsFromStackTrace
public static void setRemoveAssertJRelatedElementsFromStackTrace(boolean removeAssertJRelatedElementsFromStackTrace) Only delegate toFail.setRemoveAssertJRelatedElementsFromStackTrace(boolean)
so that Assertions offers a full feature entry point to all AssertJ Assert features (but you can useFail
if you prefer). -
fail
Only delegate toFail.fail(String)
so that Assertions offers a full feature entry point to all Assertj Assert features (but you can use Fail if you prefer). -
fail
Only delegate toFail.fail(String, Throwable)
so that Assertions offers a full feature entry point to all AssertJ features (but you can use Fail if you prefer). -
failBecauseExceptionWasNotThrown
Only delegate toFail.failBecauseExceptionWasNotThrown(Class)
so that Assertions offers a full feature entry point to all AssertJ features (but you can use Fail if you prefer).Assertions.shouldHaveThrown(Class)
can be used as a replacement. -
shouldHaveThrown
Only delegate toFail.shouldHaveThrown(Class)
so that Assertions offers a full feature entry point to all AssertJ features (but you can use Fail if you prefer). -
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 invalid input: '<' 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
-
extractProperty
Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).Typical usage is to chain
extractProperty
withfrom
method, see examples below :// extract simple property values having a java standard type (here String) assertThat(extractProperty("name", String.class).from(fellowshipOfTheRing)) .contains("Boromir", "Gandalf", "Frodo", "Legolas") .doesNotContain("Sauron", "Elrond"); // extracting property works also with user's types (here Race) assertThat(extractProperty("race", String.class).from(fellowshipOfTheRing)) .contains(HOBBIT, ELF).doesNotContain(ORC); // extract nested property on Race assertThat(extractProperty("race.name", String.class).from(fellowshipOfTheRing)) .contains("Hobbit", "Elf") .doesNotContain("Orc");
-
extractProperty
Only delegate toProperties.extractProperty(String)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useProperties
if you prefer).Typical usage is to chain
extractProperty
withfrom
method, see examples below :// extract simple property values, as no type has been defined the extracted property will be considered as Object // to define the real property type (here String) use extractProperty("name", String.class) instead. assertThat(extractProperty("name").from(fellowshipOfTheRing)) .contains("Boromir", "Gandalf", "Frodo", "Legolas") .doesNotContain("Sauron", "Elrond"); // extracting property works also with user's types (here Race), even though it will be considered as Object // to define the real property type (here String) use extractProperty("name", Race.class) instead. assertThat(extractProperty("race").from(fellowshipOfTheRing)).contains(HOBBIT, ELF).doesNotContain(ORC); // extract nested property on Race assertThat(extractProperty("race.name").from(fellowshipOfTheRing)).contains("Hobbit", "Elf").doesNotContain("Orc");
-
tuple
Utility method to build nicely aTuple
when working withAbstractIterableAssert.extracting(String...)
orAbstractObjectArrayAssert.extracting(String...)
-
setAllowExtractingPrivateFields
public static void setAllowExtractingPrivateFields(boolean allowExtractingPrivateFields) Globally sets whether
andIterableAssert#extracting(String)
should be allowed to extract private fields, if not and they try it fails with exception.ObjectArrayAssert#extracting(String)
- Parameters:
allowExtractingPrivateFields
- allow private fields extraction. 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
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 :Mapinvalid input: '<'Ring, TolkienCharacter> ringBearers = ... // init omitted assertThat(ringBearers).contains(entry(oneRing, frodo), entry(nenya, galadriel));
-
atIndex
Only delegate toIndex.atIndex(int)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useIndex
if you prefer).Typical usage :
List<Ring> elvesRings = newArrayList(vilya, nenya, narya); assertThat(elvesRings).contains(vilya, atIndex(0)).contains(nenya, atIndex(1)).contains(narya, atIndex(2));
-
offset
Assertions entry point for doubleOffset
.Typical usage :
assertThat(8.1).isEqualTo(8.0, offset(0.1));
-
offset
Assertions entry point for floatOffset
.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, offset(0.2f));
-
within
Alias foroffset(Double)
to use with isCloseTo assertions.Typical usage :
assertThat(8.1).isCloseTo(8.0, within(0.1));
-
within
Alias foroffset(Float)
to use with isCloseTo assertions.Typical usage :
assertThat(8.2f).isCloseTo(8.0f, within(0.2f));
-
within
Assertions entry point for BigDecimalOffset
to use with isCloseTo assertions.Typical usage :
assertThat(BigDecimal.TEN).isCloseTo(new BigDecimal("10.5"), within(BigDecimal.ONE));
-
within
Assertions entry point for ByteOffset
to use with isCloseTo assertions.Typical usage :
assertThat((byte)10).isCloseTo((byte)11, within((byte)1));
-
within
Assertions entry point for IntegerOffset
to use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, within(1));
-
within
Assertions entry point for ShortOffset
to use with isCloseTo assertions.Typical usage :
assertThat(10).isCloseTo(11, within(1));
-
within
Assertions entry point for LongOffset
to use with isCloseTo assertions.Typical usage :
assertThat(5l).isCloseTo(7l, within(2l));
-
withinPercentage
Assertions entry point for DoublePercentage
to use with isCloseTo assertions for percentages.Typical usage :
assertThat(11.0).isCloseTo(10.0, withinPercentage(10.0));
-
withinPercentage
Assertions entry point for IntegerPercentage
to use with isCloseTo assertions for percentages.Typical usage :
assertThat(11).isCloseTo(10, withinPercentage(10));
-
withinPercentage
Assertions entry point for LongPercentage
to use with isCloseTo assertions for percentages.Typical usage :
assertThat(11L).isCloseTo(10L, withinPercentage(10L));
-
allOf
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:
NullPointerException
- if the given array isnull
.NullPointerException
- if any of the elements in the given array isnull
.
-
allOf
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:
NullPointerException
- if the given iterable isnull
.NullPointerException
- if any of the elements in the given iterable isnull
.
-
anyOf
Only delegate toAnyOf.anyOf(Condition...)
so that Assertions offers a full feature entry point to all AssertJ features (but you can useAnyOf
if you prefer).Typical usage (
jedi
andsith
areCondition
) :assertThat("Vader").is(anyOf(jedi, sith));
-
anyOf
Creates a newAnyOf
- Type Parameters:
T
- the type of object the given condition accept.- Parameters:
conditions
- the conditions to evaluate.- Returns:
- the created
AnyOf
. - Throws:
NullPointerException
- if the given iterable isnull
.NullPointerException
- if any of the elements in the given iterable isnull
.
-
doesNotHave
Creates a newDoesNotHave
.- Parameters:
condition
- the condition to inverse.- Returns:
- The Not condition created.
-
not
Creates a newNot
.- Parameters:
condition
- the condition to inverse.- Returns:
- The Not condition created.
-
filter
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
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
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
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
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
Loads the text content of a file, so that it can be passed toassertThat(String)
.Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
assertThat(File)
.- Parameters:
file
- the file.charset
- the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
Loads the text content of a file, so that it can be passed toassertThat(String)
.Note that this will load the entire file in memory; for larger files, there might be a more efficient alternative with
assertThat(File)
.- Parameters:
file
- the file.charsetName
- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
IllegalArgumentException
- if the given character set is not supported on this platform.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
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
Loads the text content of a file into a list of strings with the default charset, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file
- the file.- Returns:
- the content of the file.
- Throws:
NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
linesOf
Loads the text content of a file into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file
- the file.charset
- the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
linesOf
Loads the text content of a file into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
file
- the file.charsetName
- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
Loads the text content of a URL, so that it can be passed toassertThat(String)
.Note that this will load the entire contents in memory.
- Parameters:
url
- the URL.charset
- the character set to use.- Returns:
- the content of the URL.
- Throws:
NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
Loads the text content of a URL, so that it can be passed toassertThat(String)
.Note that this will load the entire contents in memory.
- Parameters:
url
- the URL.charsetName
- the name of the character set to use.- Returns:
- the content of the URL.
- Throws:
IllegalArgumentException
- if the given character set is not supported on this platform.RuntimeIOException
- if an I/O exception occurs.
-
contentOf
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
Loads the text content of a URL into a list of strings with the default charset, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url
- the URL.- Returns:
- the content of the file.
- Throws:
NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
linesOf
Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url
- the URL.charset
- the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException
- if the given charset isnull
.RuntimeIOException
- if an I/O exception occurs.
-
linesOf
Loads the text content of a URL into a list of strings, each string corresponding to a line. The line endings are either \n, \r or \r\n.- Parameters:
url
- the URL.charsetName
- the name of the character set to use.- Returns:
- the content of the file.
- Throws:
NullPointerException
- if the given charset isnull
.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
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
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
-