Class AbstractAssert<SELF extends AbstractAssert<SELF,ACTUAL>,ACTUAL>
- Type Parameters:
SELF- the "self" type of this assertion class. Please read "Emulating 'self types' using Java Generics to simplify fluent API implementation" for more details.ACTUAL- the type of the "actual" value.
- All Implemented Interfaces:
Assert<SELF,,ACTUAL> Descriptable<SELF>,ExtensionPoints<SELF,ACTUAL>
- Direct Known Subclasses:
Abstract2DArrayAssert,AbstractBooleanAssert,AbstractCharSequenceAssert,AbstractClassAssert,AbstractCompletableFutureAssert,AbstractDateAssert,AbstractEnumerableAssert,AbstractFileAssert,AbstractFutureAssert,AbstractInputStreamAssert,AbstractIterableAssert,AbstractIteratorAssert,AbstractLongAdderAssert,AbstractMatcherAssert,AbstractObjectArrayAssert,AbstractObjectAssert,AbstractOptionalAssert,AbstractOptionalDoubleAssert,AbstractOptionalIntAssert,AbstractOptionalLongAssert,AbstractPeriodAssert,AbstractPredicateAssert,AbstractSpliteratorAssert,AbstractTemporalAssert,AbstractUrlAssert,AtomicBooleanAssert,AtomicIntegerAssert,AtomicLongAssert,AtomicReferenceArrayAssert,AtomicReferenceAssert,DoublePredicateAssert,IntPredicateAssert,LongPredicateAssert,RecursiveAssertionAssert,RecursiveComparisonAssert
- Author:
- Alex Ruiz, Joel Costigliola, Mikhail Mazursky, Nicolas François
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionactual()Returns actual (the object currently under test).protected booleanDeprecated.<ASSERT extends AbstractAssert<?,?>>
ASSERTasInstanceOf(InstanceOfAssertFactory<?, ASSERT> instanceOfAssertFactory) Uses anInstanceOfAssertFactoryto verify that the actual value is an instance of a given type and to produce a newAssertnarrowed to that type.asList()Deprecated.useasInstanceOf(InstanceOfAssertFactories.LIST)insteadprotected AssertionErrorassertionError(ErrorMessageFactory errorMessageFactory) asString()Returns a String assertion for thetoString()of the actual value, to allow chaining of String-specific assertions from this call.describedAs(Description description) Sets the description of the assertion that is going to be called after.The description of this assertion set withDescriptable.describedAs(String, Object...)ordescribedAs(Description).doesNotHave(Condition<? super ACTUAL> condition) Verifies that the actual value does not satisfy the given condition.doesNotHaveSameClassAs(Object other) Verifies that the actual value does not have the same class as the given object.doesNotHaveSameHashCodeAs(Object other) Verifies that the actual object does not have the same hashCode as the given object.doesNotHaveToString(String otherToString) Verifies that actualactual.toString()is not equal to the givenString.doesNotHaveToString(String expectedStringTemplate, Object... args) Verifies that actualactual.toString()is not equal to the givenString.doesNotMatch(Predicate<? super ACTUAL> predicate) Verifies that the actual object does not match the given predicate.doesNotMatch(Predicate<? super ACTUAL> predicate, String predicateDescription) Verifies that the actual object does not match the given predicate, the predicate description is used to get an informative error message.booleanDeprecated.useisEqualTo(java.lang.Object)insteadprotected <ASSERT extends AbstractAssert<?,?>>
ASSERTextracting(String propertyOrField, AssertFactory<Object, ASSERT> assertFactory) Extracts the value of given field/property from the object under test and creates a new assertion object using the given assert factory.protected <T,ASSERT extends AbstractAssert<?, ?>>
ASSERTextracting(Function<? super ACTUAL, ? extends T> extractor, AssertFactory<T, ASSERT> assertFactory) Uses the givenFunctionto extract a value from the object under test and creates a new assertion object using the given assert factory.protected AssertionErrorGenerate a custom assertion error using the information in this assertion.protected AssertionErrorfailureWithActualExpected(Object actual, Object expected, String errorMessageFormat, Object... arguments) Generate a custom assertion error using the information in this assertion, using the given actual and expected values.protected voidfailWithActualExpectedAndMessage(Object actual, Object expected, String errorMessageFormat, Object... arguments) Throw an assertion error based on information in this assertion.protected voidfailWithMessage(String errorMessage, Object... arguments) Throw an assertion error based on information in this assertion.Exposes theWritableAssertionInfoused in the current assertion for better extensibility.
When writing your own assertion class, you can use the returnedWritableAssertionInfoto change the error message and still keep the description set by the assertion user.Verifies that the actual value satisfies the given condition.inthashCode()Always returns 1.hasSameClassAs(Object other) Verifies that the actual value has the same class as the given object.hasSameHashCodeAs(Object other) Verifies that the actual object has the same hashCode as the given object.hasToString(String expectedToString) Verifies that actualactual.toString()is equal to the givenString.hasToString(String expectedStringTemplate, Object... args) Verifies that actualactual.toString()is equal to the givenStringwhenformattedwith the given arguments.protected SELFinBinary()Use binary object representation instead of standard representation in error messages.protected SELFUse hexadecimal object representation instead of standard representation in error messages.Verifies that the actual value satisfies the given condition.protected booleanisElementOfCustomAssert(StackTraceElement stackTraceElement) Verifies that the actual value is equal to the given one.isExactlyInstanceOf(Class<?> type) Verifies that the actual value is exactly an instance of the given type.Verifies that the actual value is present in the given iterable.Verifies that the actual value is present in the given array of values.isInstanceOf(Class<?> type) Verifies that the actual value is an instance of the given type.isInstanceOfAny(Class<?>... types) Verifies that the actual value is an instance of any of the given types.<T> SELFisInstanceOfSatisfying(Class<T> type, Consumer<T> requirements) Verifies that the actual value is an instance of the given type satisfying the given requirements expressed as aConsumer.Verifies that the actual value does not satisfy the given condition.isNotEqualTo(Object other) Verifies that the actual value is not equal to the given one.isNotExactlyInstanceOf(Class<?> type) Verifies that the actual value is not exactly an instance of given type.Verifies that the actual value is not present in the given iterable.Verifies that the actual value is not present in the given array of values.isNotInstanceOf(Class<?> type) Verifies that the actual value is not an instance of the given type.isNotInstanceOfAny(Class<?>... types) Verifies that the actual value is not an instance of any of the given types.Verifies that the actual value is notnull.isNotOfAnyClassIn(Class<?>... types) Verifies that the actual value type is not in given types.isNotSameAs(Object other) Verifies that the actual value is not the same as the given one, i.e., using == comparison.voidisNull()Verifies that the actual value isnull.isOfAnyClassIn(Class<?>... types) Verifies that the actual value type is in given types.Verifies that the actual value is the same as the given one, i.e., using == comparison.Verifies that the actual object matches the given predicate.Verifies that the actual object matches the given predicate, the predicate description is used to get an informative error message.protected <E> AbstractListAssert<?, List<? extends E>, E, ObjectAssert<E>> newListAssertInstance(List<? extends E> newActual) Create aAbstractListAssertfrom the given list.overridingErrorMessage(String newErrorMessage, Object... args) Overrides AssertJ default error message by the given one.overridingErrorMessage(Supplier<String> supplier) Overrides AssertJ default error message by the given one.final SELFVerifies that the actual object satisfied the given requirements expressed asConsumers.Verifies that the actual value satisfies the given condition.final SELFsatisfies(ThrowingConsumer<? super ACTUAL>... assertions) Verifies that the actual object satisfied the given requirements expressed asThrowingConsumers.final SELFsatisfiesAnyOf(Consumer<? super ACTUAL>... assertions) Verifies that the actual object under test satisfies at least one of the given assertions group expressed asConsumers.final SELFsatisfiesAnyOf(ThrowingConsumer<? super ACTUAL>... assertions) Verifies that the actual object under test satisfies at least one of the given assertions group expressed asThrowingConsumers.protected SELFsatisfiesAnyOfForProxy(Consumer<? super ACTUAL>[] assertionsGroups) protected SELFsatisfiesForProxy(Consumer<? super ACTUAL>[] assertionsGroups) static voidsetCustomRepresentation(Representation customRepresentation) static voidsetDescriptionConsumer(Consumer<Description> descriptionConsumer) static voidsetPrintAssertionsDescription(boolean printAssertionsDescription) protected voidthrowAssertionError(ErrorMessageFactory errorMessageFactory) Utility method to throw anAssertionErrorgiven aBasicErrorMessageFactory.usingComparator(Comparator<? super ACTUAL> customComparator) Use the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) Use the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.Revert to standard comparison for the incoming assertion checks.usingEquals(BiPredicate<? super ACTUAL, ? super ACTUAL> predicate) Uses the given customBiPredicateinstead of relying on actual type Aequalsmethod for incoming assertion checks.usingEquals(BiPredicate<? super ACTUAL, ? super ACTUAL> predicate, String customEqualsDescription) Uses the given customBiPredicateinstead of relying on actual type Aequalsmethod for incoming assertion checks.protected RecursiveAssertionAssertprotected RecursiveAssertionAssertusingRecursiveAssertion(RecursiveAssertionConfiguration recursiveAssertionConfiguration) protected RecursiveComparisonAssert<?> protected RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) withFailMessage(String newErrorMessage, Object... args) Alternative method foroverridingErrorMessage(java.lang.String, java.lang.Object...)withFailMessage(Supplier<String> supplier) Alternative method foroverridingErrorMessage(java.lang.String, java.lang.Object...)withRepresentation(Representation representation) Use the givenRepresentationto describe/represent values in AssertJ error messages.In case of an assertion error, a thread dump will be printed toSystem.err.Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.assertj.core.api.Descriptable
as, as, as, describedAs, describedAs
-
Field Details
-
throwUnsupportedExceptionOnEquals
public static boolean throwUnsupportedExceptionOnEquals -
objects
-
info
-
actual
-
myself
-
-
Constructor Details
-
AbstractAssert
-
-
Method Details
-
getWritableAssertionInfo
Exposes theWritableAssertionInfoused in the current assertion for better extensibility.
When writing your own assertion class, you can use the returnedWritableAssertionInfoto change the error message and still keep the description set by the assertion user.- Returns:
- the
WritableAssertionInfoused in the current assertion
-
failWithMessage
Throw an assertion error based on information in this assertion. Equivalent to:throw failure(errorMessage, arguments);This method is a thin wrapper around
failure()- see that method for a more detailed description.Note that generally speaking, using
failure()directly is preferable to using this wrapper method, as the compiler and other code analysis tools will be able to tell that the statement will never return normally and respond appropriately.- Parameters:
errorMessage- the error message to formatarguments- the arguments referenced by the format specifiers in the errorMessage string.- See Also:
-
failure
Generate a custom assertion error using the information in this assertion.This is a utility method to ease writing custom assertions classes using
String.format(String, Object...)specifiers in error message.Moreover, this method honors any description set with
Descriptable.as(String, Object...)or overridden error message defined by the user withoverridingErrorMessage(String, Object...).Example:
public TolkienCharacterAssert hasName(String name) { // check that actual TolkienCharacter we want to make assertions on is not null. isNotNull(); // check condition if (!actual.getName().equals(name)) { failWithMessage("Expected character's name to be <%s> but was <%s>", name, actual.getName()); } // return the current assertion for method chaining return this; }- Parameters:
errorMessage- the error message to formatarguments- the arguments referenced by the format specifiers in the errorMessage string.- Returns:
- The generated assertion error.
- See Also:
-
failWithActualExpectedAndMessage
@Contract("_, _, _, _ -> fail") protected void failWithActualExpectedAndMessage(Object actual, Object expected, String errorMessageFormat, Object... arguments) Throw an assertion error based on information in this assertion. Equivalent to:throw failureWithActualExpected(actual, expected, errorMessageFormat, arguments);This method is a thin wrapper around
failureWithActualExpected()- see that method for a more detailed description. Note that generally speaking, usingfailureWithActualExpected()directly is preferable to using this wrapper method, as the compiler and other code analysis tools will be able to tell that the statement will never return normally and respond appropriately.- Parameters:
actual- the actual object that was found during the testexpected- the object that was expectederrorMessageFormat- the error message to formatarguments- the arguments referenced by the format specifiers in the errorMessage string.- See Also:
-
failureWithActualExpected
protected AssertionError failureWithActualExpected(Object actual, Object expected, String errorMessageFormat, Object... arguments) Generate a custom assertion error using the information in this assertion, using the given actual and expected values.This is a utility method to ease writing custom assertions classes using
String.format(String, Object...)specifiers in error message with actual and expected values.Moreover, this method honors any description set with
Descriptable.as(String, Object...)or overridden error message defined by the user withoverridingErrorMessage(String, Object...).This method also sets the "actual" and "expected" fields of the assertion if available (eg, if OpenTest4J is on the path). This aids IDEs to produce visual diffs of the resulting values.
Example:
public TolkienCharacterAssert hasName(String name) { // check that actual TolkienCharacter we want to make assertions on is not null. isNotNull(); // check condition if (!actual.getName().equals(name)) { throw failureWithActualExpected(actual.getName(), name, "Expected character's name to be <%s> but was <%s>", name, actual.getName()); } // return the current assertion for method chaining return this; }- Parameters:
actual- the actual object that was found during the testexpected- the object that was expectederrorMessageFormat- the error message to formatarguments- the arguments referenced by the format specifiers in the errorMessage string.- Returns:
- The generated assertion error.
- See Also:
-
throwAssertionError
Utility method to throw anAssertionErrorgiven aBasicErrorMessageFactory.Instead of writing ...
... you can simply write :throw Failures.instance().failure(info, ShouldBePresent.shouldBePresent());throwAssertionError(info, ShouldBePresent.shouldBePresent());- Parameters:
errorMessageFactory- used to define the error message.- Throws:
AssertionError- with a message corresponding to the givenBasicErrorMessageFactory.
-
assertionError
-
isElementOfCustomAssert
-
inHexadecimal
Use hexadecimal object representation instead of standard representation in error messages.It can be useful when comparing UNICODE characters - many unicode chars have duplicate characters assigned, it is thus impossible to find differences from the standard error message:
With standard message:
assertThat("µµµ").contains("μμμ"); java.lang.AssertionError: Expecting: <"µµµ"> to contain: <"μμμ">With Hexadecimal message:
assertThat("µµµ").inHexadecimal().contains("μμμ"); java.lang.AssertionError: Expecting: <"['00B5', '00B5', '00B5']"> to contain: <"['03BC', '03BC', '03BC']">- Returns:
thisassertion object.
-
inBinary
Use binary object representation instead of standard representation in error messages.Example:
assertThat(1).inBinary().isEqualTo(2); org.junit.ComparisonFailure: Expected :0b00000000_00000000_00000000_00000010 Actual :0b00000000_00000000_00000000_00000001- Returns:
thisassertion object.
-
describedAs
Sets the description of the assertion that is going to be called after.You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
This overloaded version of "describedAs" offers more flexibility than the one taking a
Stringby allowing users to pass their own implementation of a description. For example, a description that creates its value lazily, only when an assertion failure occurs.- Specified by:
describedAsin interfaceDescriptable<SELF extends AbstractAssert<SELF,ACTUAL>> - Parameters:
description- the new description to set.- Returns:
thisobject.
-
isEqualTo
Verifies that the actual value is equal to the given one.Example:
// assertions succeed assertThat("abc").isEqualTo("abc"); assertThat(new HashMap<String, Integer>()).isEqualTo(new HashMap<String, Integer>()); // assertions fail assertThat("abc").isEqualTo("123"); assertThat(new ArrayList<String>()).isEqualTo(1); -
isNotEqualTo
Verifies that the actual value is not equal to the given one.Example:
// assertions succeed assertThat("abc").isNotEqualTo("123"); assertThat(new ArrayList<String>()).isNotEqualTo(1); // assertions fail assertThat("abc").isNotEqualTo("abc"); assertThat(new HashMap<String, Integer>()).isNotEqualTo(new HashMap<String, Integer>());- Specified by:
isNotEqualToin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
other- the given value to compare the actual value to.- Returns:
thisassertion object.
-
isNull
public void isNull()Verifies that the actual value isnull.Example:
String value = null; // assertion succeeds assertThat(value).isNull(); // assertions fail assertThat("abc").isNull(); assertThat(new HashMap<String, Integer>()).isNull(); -
isNotNull
Verifies that the actual value is notnull.Example:
// assertions succeed assertThat("abc").isNotNull(); assertThat(new HashMap<String, Integer>()).isNotNull(); // assertions fails String value = null; assertThat(value).isNotNull(); -
isSameAs
Verifies that the actual value is the same as the given one, i.e., using == comparison.Example:
// Name is a class with first and last fields, two Names are equals if both first and last are equals. Name tyrion = new Name("Tyrion", "Lannister"); Name alias = tyrion; Name clone = new Name("Tyrion", "Lannister"); // assertions succeed: assertThat(tyrion).isSameAs(alias) .isEqualTo(clone); // assertion fails: assertThat(tyrion).isSameAs(clone); -
isNotSameAs
Verifies that the actual value is not the same as the given one, i.e., using == comparison.Example:
// Name is a class with first and last fields, two Names are equals if both first and last are equals. Name tyrion = new Name("Tyrion", "Lannister"); Name alias = tyrion; Name clone = new Name("Tyrion", "Lannister"); // assertions succeed: assertThat(clone).isNotSameAs(tyrion) .isEqualTo(tyrion); // assertion fails: assertThat(alias).isNotSameAs(tyrion);- Specified by:
isNotSameAsin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
other- the given value to compare the actual value to.- Returns:
thisassertion object.
-
isIn
Verifies that the actual value is present in the given array of values.This assertion always fails if the given array of values is empty.
Example:
Ring[] elvesRings = new Ring[] { vilya, nenya, narya }; // assertion succeeds assertThat(nenya).isIn(elvesRings); // assertions fail assertThat(oneRing).isIn(elvesRings); assertThat(oneRing).isIn(new Ring[0]); -
isNotIn
Verifies that the actual value is not present in the given array of values.This assertion always succeeds if the given array of values is empty.
Example:
Ring[] elvesRings = new Ring[] { vilya, nenya, narya }; // assertions succeed assertThat(oneRing).isNotIn(elvesRings); assertThat(oneRing).isNotIn(new Ring[0]); // assertions fails: assertThat(nenya).isNotIn(elvesRings); -
isIn
Verifies that the actual value is present in the given iterable.This assertion always fails if the given iterable is empty.
Example:
Iterable<Ring> elvesRings = list(vilya, nenya, narya); // assertion succeeds assertThat(nenya).isIn(elvesRings); // assertions fail: assertThat(oneRing).isIn(elvesRings); assertThat(oneRing).isIn(emptyList()); -
isNotIn
Verifies that the actual value is not present in the given iterable.This assertion always succeeds if the given iterable is empty.
Example:
Iterable<Ring> elvesRings = list(vilya, nenya, narya); // assertions succeed: assertThat(oneRing).isNotIn(elvesRings); assertThat(oneRing).isNotIn(emptyList()); // assertions fails: assertThat(nenya).isNotIn(elvesRings); -
is
Verifies that the actual value satisfies the given condition. This method is an alias for.ExtensionPoints.has(Condition)- Specified by:
isin interfaceExtensionPoints<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
-
isNot
Verifies that the actual value does not satisfy the given condition. This method is an alias for.ExtensionPoints.doesNotHave(Condition)- Specified by:
isNotin interfaceExtensionPoints<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
-
has
Verifies that the actual value satisfies the given condition. This method is an alias for.ExtensionPoints.is(Condition)- Specified by:
hasin interfaceExtensionPoints<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
-
doesNotHave
Verifies that the actual value does not satisfy the given condition. This method is an alias for.ExtensionPoints.isNot(Condition)- Specified by:
doesNotHavein interfaceExtensionPoints<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
-
satisfies
Verifies that the actual value satisfies the given condition. This method is an alias for.ExtensionPoints.is(Condition)Example:
// Given Condition<String> fairyTale = new Condition<>(s -> s.startsWith("Once upon a time"), "fairy tale start"); // When String littleRedCap = "Once upon a time there was a dear little girl ..."; // Then assertThat(littleRedCap).satisfies(fairyTale);- Specified by:
satisfiesin interfaceExtensionPoints<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
condition- the given condition.- Returns:
this ExtensionPointsobject.- See Also:
-
asInstanceOf
public <ASSERT extends AbstractAssert<?,?>> ASSERT asInstanceOf(InstanceOfAssertFactory<?, ASSERT> instanceOfAssertFactory) Uses anInstanceOfAssertFactoryto verify that the actual value is an instance of a given type and to produce a newAssertnarrowed to that type.InstanceOfAssertFactoriesprovides static factories for all the types supported byAssertions#assertThat.Additional factories can be created with custom
InstanceOfAssertFactoryinstances.Example:
// assertions succeeds Object string = "abc"; assertThat(string).asInstanceOf(InstanceOfAssertFactories.STRING).startsWith("ab"); Object integer = 1; assertThat(integer).asInstanceOf(InstanceOfAssertFactories.INTEGER).isNotZero(); // assertions fails assertThat("abc").asInstanceOf(InstanceOfAssertFactories.INTEGER);- Specified by:
asInstanceOfin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Type Parameters:
ASSERT- the type of the resultingAssert.- Parameters:
instanceOfAssertFactory- the factory which verifies the type and creates the newAssert.- Returns:
- the narrowed
Assertinstance. - See Also:
-
isInstanceOf
Verifies that the actual value is an instance of the given type.Example:
// assertions succeed assertThat("abc").isInstanceOf(String.class); assertThat(new HashMap<String, Integer>()).isInstanceOf(HashMap.class); assertThat(new HashMap<String, Integer>()).isInstanceOf(Map.class); // assertions fail assertThat(1).isInstanceOf(String.class); assertThat(new ArrayList<String>()).isInstanceOf(LinkedList.class);- Specified by:
isInstanceOfin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isInstanceOfSatisfying
Verifies that the actual value is an instance of the given type satisfying the given requirements expressed as aConsumer.This is useful to perform a group of assertions on a single object after checking its runtime type.
Example:
// second constructor parameter is the light saber color Object yoda = new Jedi("Yoda", "Green"); Object luke = new Jedi("Luke Skywalker", "Green"); Consumer<Jedi> jediRequirements = jedi -> { assertThat(jedi.getLightSaberColor()).isEqualTo("Green"); assertThat(jedi.getName()).doesNotContain("Dark"); }; // assertions succeed: assertThat(yoda).isInstanceOfSatisfying(Jedi.class, jediRequirements); assertThat(luke).isInstanceOfSatisfying(Jedi.class, jediRequirements); // assertions fail: Jedi vader = new Jedi("Vader", "Red"); assertThat(vader).isInstanceOfSatisfying(Jedi.class, jediRequirements); // not a Jedi ! assertThat("foo").isInstanceOfSatisfying(Jedi.class, jediRequirements);- Specified by:
isInstanceOfSatisfyingin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Type Parameters:
T- the generic type to check the actual value against.- Parameters:
type- the type to check the actual value against.requirements- the requirements expressed as aConsumer.- Returns:
- this assertion object.
-
isInstanceOfAny
Verifies that the actual value is an instance of any of the given types.Example:
// assertions succeed assertThat("abc").isInstanceOfAny(String.class, Integer.class); assertThat(new ArrayList<String>()).isInstanceOfAny(LinkedList.class, ArrayList.class); assertThat(new HashMap<String, Integer>()).isInstanceOfAny(TreeMap.class, Map.class); // assertions fail assertThat(1).isInstanceOfAny(Double.class, Float.class); assertThat(new ArrayList<String>()).isInstanceOfAny(LinkedList.class, Vector.class);- Specified by:
isInstanceOfAnyin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
types- the types to check the actual value against.- Returns:
- this assertion object.
-
isNotInstanceOf
Verifies that the actual value is not an instance of the given type.Example:
// assertions succeed assertThat(1).isNotInstanceOf(Double.class); assertThat(new ArrayList<String>()).isNotInstanceOf(LinkedList.class); // assertions fail assertThat("abc").isNotInstanceOf(String.class); assertThat(new HashMap<String, Integer>()).isNotInstanceOf(HashMap.class); assertThat(new HashMap<String, Integer>()).isNotInstanceOf(Map.class);- Specified by:
isNotInstanceOfin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isNotInstanceOfAny
Verifies that the actual value is not an instance of any of the given types.Example:
// assertions succeed assertThat(1).isNotInstanceOfAny(Double.class, Float.class); assertThat(new ArrayList<String>()).isNotInstanceOfAny(LinkedList.class, Vector.class); // assertions fail assertThat(1).isNotInstanceOfAny(Double.class, Integer.class); assertThat(new ArrayList<String>()).isNotInstanceOfAny(LinkedList.class, ArrayList.class); assertThat(new HashMap<String, Integer>()).isNotInstanceOfAny(TreeMap.class, Map.class);- Specified by:
isNotInstanceOfAnyin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
types- the types to check the actual value against.- Returns:
- this assertion object.
-
hasSameClassAs
Verifies that the actual value has the same class as the given object.Example:
// assertions succeed assertThat(1).hasSameClassAs(2); assertThat("abc").hasSameClassAs("123"); assertThat(new ArrayList<String>()).hasSameClassAs(new ArrayList<Integer>()); // assertions fail assertThat(1).hasSameClassAs("abc"); assertThat(new ArrayList<String>()).hasSameClassAs(new LinkedList<String>());- Specified by:
hasSameClassAsin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
other- the object to check type against.- Returns:
- this assertion object.
-
hasToString
Verifies that actualactual.toString()is equal to the givenString.Example :
CartoonCharacter homer = new CartoonCharacter("Homer"); // Instead of writing ... assertThat(homer.toString()).isEqualTo("Homer"); // ... you can simply write: assertThat(homer).hasToString("Homer");- Specified by:
hasToStringin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
expectedToString- the expected String description of actual.- Returns:
- this assertion object.
-
hasToString
Verifies that actualactual.toString()is equal to the givenStringwhenformattedwith the given arguments.Example:
Foo foo = new Foo(); FooWrapper wrapper = new FooWrapper(foo); assertThat(wrapper).hasToString("FooWrapper[foo=%s]", foo);- Specified by:
hasToStringin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
expectedStringTemplate- the format string to use.args- the arguments to interpolate into the format string.- Returns:
- this assertion object.
-
doesNotHaveToString
Verifies that actualactual.toString()is not equal to the givenString.Example :
CartoonCharacter homer = new CartoonCharacter("Homer"); // Instead of writing ... assertThat(homer.toString()).isNotEqualTo("Marge"); // ... you can simply write: assertThat(homer).doesNotHaveToString("Marge");- Specified by:
doesNotHaveToStringin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
otherToString- the String to check against.- Returns:
- this assertion object.
-
doesNotHaveToString
Verifies that actualactual.toString()is not equal to the givenString.Example:
Foo foo = new Foo(); Bar bar = new Bar(); FooBarWrapper wrapper = new FooBarWrapper(bar); assertThat(wrapper).doesNotHaveToString("FooBarWrapper[%s]", foo);- Specified by:
doesNotHaveToStringin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
expectedStringTemplate- the format string to use.args- the arguments to interpolate into the format string.- Returns:
- this assertion object.
-
doesNotHaveSameClassAs
Verifies that the actual value does not have the same class as the given object.Example:
// assertions succeed assertThat(1).doesNotHaveSameClassAs("abc"); assertThat(new ArrayList<String>()).doesNotHaveSameClassAs(new LinkedList<String>()); // assertions fail assertThat(1).doesNotHaveSameClassAs(2); assertThat("abc").doesNotHaveSameClassAs("123"); assertThat(new ArrayList<String>()).doesNotHaveSameClassAs(new ArrayList<Integer>());- Specified by:
doesNotHaveSameClassAsin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
other- the object to check type against.- Returns:
- this assertion object.
-
isExactlyInstanceOf
Verifies that the actual value is exactly an instance of the given type.Example:
// assertions succeed assertThat("abc").isExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isExactlyInstanceOf(ArrayList.class); assertThat(new HashMap<String, Integer>()).isExactlyInstanceOf(HashMap.class); // assertions fail assertThat(1).isExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isExactlyInstanceOf(List.class); assertThat(new HashMap<String, Integer>()).isExactlyInstanceOf(Map.class);- Specified by:
isExactlyInstanceOfin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isNotExactlyInstanceOf
Verifies that the actual value is not exactly an instance of given type.Example:
// assertions succeed assertThat(1).isNotExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isNotExactlyInstanceOf(List.class); assertThat(new HashMap<String, Integer>()).isNotExactlyInstanceOf(Map.class); // assertions fail assertThat("abc").isNotExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isNotExactlyInstanceOf(ArrayList.class); assertThat(new HashMap<String, Integer>()).isNotExactlyInstanceOf(HashMap.class);- Specified by:
isNotExactlyInstanceOfin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isOfAnyClassIn
Verifies that the actual value type is in given types.Example:
// assertions succeed assertThat(new HashMap<String, Integer>()).isOfAnyClassIn(HashMap.class, TreeMap.class); assertThat(new ArrayList<String>()).isOfAnyClassIn(ArrayList.class, LinkedList.class); // assertions fail assertThat(new HashMap<String, Integer>()).isOfAnyClassIn(TreeMap.class, Map.class); assertThat(new ArrayList<String>()).isOfAnyClassIn(LinkedList.class, List.class);- Specified by:
isOfAnyClassInin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
types- the types to check the actual value against.- Returns:
- this assertion object.
-
isNotOfAnyClassIn
Verifies that the actual value type is not in given types.Example:
// assertions succeed assertThat(new HashMap<String, Integer>()).isNotOfAnyClassIn(Map.class, TreeMap.class); assertThat(new ArrayList<String>()).isNotOfAnyClassIn(LinkedList.class, List.class); // assertions fail assertThat(new HashMap<String, Integer>()).isNotOfAnyClassIn(HashMap.class, TreeMap.class); assertThat(new ArrayList<String>()).isNotOfAnyClassIn(ArrayList.class, LinkedList.class);- Specified by:
isNotOfAnyClassInin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
types- the types to check the actual value against.- Returns:
- this assertion object.
-
asList
Deprecated.useasInstanceOf(InstanceOfAssertFactories.LIST)insteadVerifies that the actual value is an instance of List, and returns a list assertion, to allow chaining of list-specific assertions from this call.Example :
Object sortedListAsObject = Arrays.asList(1, 2, 3); // assertion succeeds assertThat(sortedListAsObject).asList().isSorted(); Object unsortedListAsObject = Arrays.asList(3, 1, 2); // assertions fails assertThat(unsortedListAsObject).asList().isSorted(); -
asString
Returns a String assertion for thetoString()of the actual value, to allow chaining of String-specific assertions from this call.Example :
Object stringAsObject = "hello world"; // assertion succeeds assertThat(stringAsObject).asString().contains("hello"); // assertions fails assertThat(stringAsObject).asString().contains("holla"); -
descriptionText
The description of this assertion set withDescriptable.describedAs(String, Object...)ordescribedAs(Description).- Returns:
- the description String representation of this assertion.
-
overridingErrorMessage
Overrides AssertJ default error message by the given one.You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
The new error message is built using
String.format(String, Object...)if you provide args parameter (if you don't, the error message is taken as it is).Example:
assertThat(player.isRookie()).overridingErrorMessage("Expecting Player <%s> to be a rookie but was not.", player) .isTrue();- Parameters:
newErrorMessage- the error message that will replace the default one provided by Assertj.args- the args used to fill error message as inString.format(String, Object...).- Returns:
- this assertion object.
-
overridingErrorMessage
Overrides AssertJ default error message by the given one.The new error message is only built if the assertion fails (by consuming the given supplier), this is useful if building messages is expensive.
You must set the message before calling the assertion otherwise it is ignored as the failing assertion breaks the call chain by throwing an
AssertionError.Example:
assertThat(player.isRookie()).overridingErrorMessage(() -> "Expecting Player to be a rookie but was not.") .isTrue();- Parameters:
supplier- the supplier supplies error message that will replace the default one provided by Assertj.- Returns:
- this assertion object.
-
withFailMessage
Alternative method foroverridingErrorMessage(java.lang.String, java.lang.Object...)You must set it before calling the assertion otherwise it is ignored as the failing assertion breaks the chained call by throwing an AssertionError.
Example:
assertThat(player.isRookie()).withFailMessage("Expecting Player <%s> to be a rookie but was not.", player) .isTrue();- Parameters:
newErrorMessage- the error message that will replace the default one provided by Assertj.args- the args used to fill error message as inString.format(String, Object...).- Returns:
- this assertion object.
-
withFailMessage
Alternative method foroverridingErrorMessage(java.lang.String, java.lang.Object...)The new error message is only built if the assertion fails (by consuming the given supplier), this is useful if building messages is expensive.
You must set the message before calling the assertion otherwise it is ignored as the failing assertion breaks the call chain by throwing an
AssertionError.Example:
assertThat(player.isRookie()).withFailMessage(() -> "Expecting Player to be a rookie but was not.") .isTrue();- Parameters:
supplier- the supplier supplies error message that will replace the default one provided by Assertj.- Returns:
- this assertion object.
-
usingComparator
Use the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.The custom comparator is bound to assertion instance, meaning that if a new assertion instance is created, the default comparison strategy will be used.
Examples :
// frodo and sam are instances of Character with Hobbit race (obviously :). // raceComparator implements Comparator<Character> assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam);- Specified by:
usingComparatorin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
customComparator- the comparator to use for the incoming assertion checks.- Returns:
thisassertion object.
-
usingComparator
public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) Use the given custom comparator instead of relying on actual type A equals method for incoming assertion checks.The custom comparator is bound to the current assertion chain, meaning that if a new assertion instance is created, the default comparison strategy will be used.
Examples :
// frodo and sam are instances of Character with Hobbit race (obviously :). // raceComparator implements Comparator<Character> assertThat(frodo).usingComparator(raceComparator, "Hobbit Race Comparator").isEqualTo(sam);- Specified by:
usingComparatorin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
customComparator- the comparator to use for the incoming assertion checks.customComparatorDescription- comparator description to be used in assertion error messages- Returns:
thisassertion object.
-
usingEquals
Uses the given customBiPredicateinstead of relying on actual type Aequalsmethod for incoming assertion checks.The custom equals is bound to the current assertion chain, meaning that if a new assertion instance is created, the default comparison strategy will be used.
Examples:
// frodo and sam are instances of Character of Hobbit race (obviously :). assertThat(frodo).usingEquals((f, s) -> f.race() == s.race()).isEqualTo(sam);- Specified by:
usingEqualsin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
predicate- the predicate to use for the incoming assertion checks.- Returns:
thisassertion object.
-
usingEquals
public SELF usingEquals(BiPredicate<? super ACTUAL, ? super ACTUAL> predicate, String customEqualsDescription) Uses the given customBiPredicateinstead of relying on actual type Aequalsmethod for incoming assertion checks. The given description is present in the assertion error if the assertion fails.The custom equals is bound to the current assertion chain, meaning that if a new assertion instance is created, the default comparison strategy will be used.
Examples:
// frodo and sam are instances of Character of Hobbit race (obviously :). assertThat(frodo).usingEquals((f, s) -> f.race() == s.race(), "comparing race").isEqualTo(sam);- Specified by:
usingEqualsin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
predicate- the predicate to use for the incoming assertion checks.customEqualsDescription- comparator description to be used in assertion error messages- Returns:
thisassertion object.
-
usingDefaultComparator
Revert to standard comparison for the incoming assertion checks.This method should be used to disable a custom comparison strategy set by calling
usingComparator.- Specified by:
usingDefaultComparatorin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Returns:
thisassertion object.
-
withThreadDumpOnError
In case of an assertion error, a thread dump will be printed toSystem.err.Example :
assertThat("Messi").withThreadDumpOnError().isEqualTo("Ronaldo");will print a thread dump, something similar to this:
"JDWP Command Reader" java.lang.Thread.State: RUNNABLE "JDWP Event Helper Thread" java.lang.Thread.State: RUNNABLE "JDWP Transport Listener: dt_socket" java.lang.Thread.State: RUNNABLE "Signal Dispatcher" java.lang.Thread.State: RUNNABLE "Finalizer" java.lang.Thread.State: WAITING at java.lang.Object.wait(Native Method) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:189) "Reference Handler" java.lang.Thread.State: WAITING at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:503) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133) "main" java.lang.Thread.State: RUNNABLE at sun.management.ThreadImpl.dumpThreads0(Native Method) at sun.management.ThreadImpl.dumpAllThreads(ThreadImpl.java:446) at org.assertj.core.internal.Failures.threadDumpDescription(Failures.java:193) at org.assertj.core.internal.Failures.printThreadDumpIfNeeded(Failures.java:141) at org.assertj.core.internal.Failures.failure(Failures.java:91) at org.assertj.core.internal.Objects.assertEqual(Objects.java:314) at org.assertj.core.api.AbstractAssert.isEqualTo(AbstractAssert.java:198) at org.assertj.examples.ThreadDumpOnErrorExample.main(ThreadDumpOnErrorExample.java:28)- Specified by:
withThreadDumpOnErrorin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Returns:
- this assertion object.
-
withRepresentation
Use the givenRepresentationto describe/represent values in AssertJ error messages.The usual way to introduce a new
Representationis to extendStandardRepresentationand override any existingtoStringOfmethods that don't suit you. For example you can controlDateformatting by overridingStandardRepresentation.toStringOf(Date)).You can also control other types format by overriding
StandardRepresentation.toStringOf(Object)) calling your formatting method first and then fall back to the default representation by callingsuper.toStringOf(Object).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"; // fall back to default formatting return super.toStringOf(o); } // change String representation @Override protected String toStringOf(String s) { return "$" + s + "$"; } } // next assertion fails with error : "expected:<[null]> but was:<[Example]>" Example example = new Example(); assertThat(example).withRepresentation(new CustomRepresentation()) .isNull(); // example is not null ! // next assertion fails ... assertThat("foo").withRepresentation(new CustomRepresentation()) .startsWith("bar"); // ... with error : Expecting: <$foo$> to start with: <$bar$>- Specified by:
withRepresentationin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
representation- Describe/represent values in AssertJ error messages.- Returns:
- this assertion object.
-
equals
Deprecated.useisEqualTo(java.lang.Object)instead- Specified by:
equalsin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Overrides:
equalsin classObject- Throws:
UnsupportedOperationException- if this method is called.
-
hashCode
public int hashCode()Always returns 1. -
matches
Verifies that the actual object matches the given predicate.Example:
assertThat(player).matches(p -> p.isRookie());- Parameters:
predicate- thePredicateto match- Returns:
thisassertion object.- Throws:
AssertionError- ifactualdoes not match the givenPredicate.NullPointerException- if givenPredicateis null.
-
matches
Verifies that the actual object matches the given predicate, the predicate description is used to get an informative error message.Example:
assertThat(player).matches(p -> p.isRookie(), "is rookie");The error message contains the predicate description, in our example, it is:
Expecting: <player> to match 'is rookie' predicate.- Parameters:
predicate- thePredicateto matchpredicateDescription- a description of thePredicateused in the error message- Returns:
thisassertion object.- Throws:
AssertionError- ifactualdoes not match the givenPredicate.NullPointerException- if givenPredicateis null.NullPointerException- if given predicateDescription is null.
-
doesNotMatch
Verifies that the actual object does not match the given predicate.Example:
assertThat(player).doesNotMatch(p -> p.isRookie());- Parameters:
predicate- thePredicatenot to match- Returns:
thisassertion object.- Throws:
AssertionError- ifactualmatches the givenPredicate.NullPointerException- if givenPredicateis null.
-
doesNotMatch
Verifies that the actual object does not match the given predicate, the predicate description is used to get an informative error message.Example:
assertThat(player).doesNotMatch(p -> p.isRookie(), "is rookie");The error message contains the predicate description, in our example, it is:
Expecting: <player> not to match 'is rookie' predicate.- Parameters:
predicate- thePredicatenot to matchpredicateDescription- a description of thePredicateused in the error message- Returns:
thisassertion object.- Throws:
AssertionError- ifactualmatches the givenPredicate.NullPointerException- if givenPredicateis null.NullPointerException- if given predicateDescription is null.
-
satisfies
Verifies that the actual object satisfied the given requirements expressed asConsumers.This is useful to perform a group of assertions on a single object, each passed assertion is evaluated and all failures are reported (to be precise each assertion can lead to one failure max).
Grouping assertions example :
// second constructor parameter is the light saber color Jedi yoda = new Jedi("Yoda", "Green"); Jedi luke = new Jedi("Luke Skywalker", "Green"); Consumer<Jedi> redLightSaber = jedi -> assertThat(jedi.getLightSaberColor()).isEqualTo("Red"); Consumer<Jedi> greenLightSaber = jedi -> assertThat(jedi.getLightSaberColor()).isEqualTo("Green"); Consumer<Jedi> notDarth = jedi -> assertThat(jedi.getName()).doesNotContain("Darth"); Consumer<Jedi> darth = jedi -> assertThat(jedi.getName()).contains("Darth"); // assertions succeed: assertThat(yoda).satisfies(greenLightSaber); assertThat(luke).satisfies(greenLightSaber, notDarth); // assertions fail: Jedi vader = new Jedi("Darth Vader", "Red"); assertThat(vader).satisfies(greenLightSaber); assertThat(vader).satisfies(darth, greenLightSaber); assertThat(vader).satisfies(greenLightSaber, notDarth);In the following example,
satisfiesprevents the need to define a local variable in order to run multiple assertions:// no need to define team.getPlayers().get(0).getStats() as a local variable assertThat(team.getPlayers().get(0).getStats()).satisfies(stats -> assertThat(stats.pointPerGame).isGreaterThan(25.7), stats -> assertThat(stats.assistsPerGame).isGreaterThan(7.2), stats -> assertThat(stats.reboundsPerGame).isBetween(9, 12));- Parameters:
requirements- to assert on the actual object - must not be null.- Returns:
- this assertion object.
- Throws:
NullPointerException- if any given Consumer is null
-
satisfies
Verifies that the actual object satisfied the given requirements expressed asThrowingConsumers.This is the same assertion as
satisfies(Consumer[])except that aThrowingConsumerrethrows checked exceptions asRuntimeException. More precisely,RuntimeExceptionandAssertionErrorare rethrown as they are andThrowablewrapped in aRuntimeException. If each assertion is passed as a separate argument, all of them will be evaluated and assertion error will contain all failures.Example:
// read() throws IOException ThrowingConsumer<Reader> hasReachedEOF = reader -> assertThat(reader.read()).isEqualTo(-1); ThrowingConsumer<Reader> nextCharacterA = reader -> assertThat(reader.read()).isEqualTo('a'); ThrowingConsumer<Reader> nextCharacterB = reader -> assertThat(reader.read()).isEqualTo('b'); ThrowingConsumer<Reader> nextCharacterZ = reader -> assertThat(reader.read()).isEqualTo('z'); // alphabet.txt contains: abcdefghijklmnopqrstuvwxyz // empty.txt is empty // assertion succeeds: assertThat(new FileReader("empty.txt")).satisfies(hasReachedEOF); assertThat(new FileReader("alphabet.txt")).satisfies(nextCharacterA, nextCharacterB); // assertion fails: assertThat(new FileReader("alphabet.txt")).satisfies(nextCharacterA, hasReachedEOF); assertThat(new FileReader("alphabet.txt")).satisfies(nextCharacterB, nextCharacterZ);- Parameters:
assertions- the group of assertions to run against the object under test - must not be null.- Returns:
- this assertion object.
- Throws:
IllegalArgumentException- if any given assertions group is nullRuntimeException- rethrown as is by the givenThrowingConsumeror wrapping anyThrowable.AssertionError- rethrown as is by the givenThrowingConsumer- Since:
- 3.21.0
-
satisfiesForProxy
- Throws:
AssertionError
-
satisfiesAnyOf
Verifies that the actual object under test satisfies at least one of the given assertions group expressed asConsumers.This allows users to perform OR like assertions since only one the assertions group has to be met.
Overriding error messageis not supported as it would prevent from getting the error messages of the failing assertions, these are valuable to figure out what went wrong.
Describing the assertion is supported (for example withDescriptable.as(String, Object...)).Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", HOBBIT); Consumer<TolkienCharacter> isHobbit = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(HOBBIT); Consumer<TolkienCharacter> isElf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(ELF); Consumer<TolkienCharacter> isDwarf = tolkienCharacter -> assertThat(tolkienCharacter.getRace()).isEqualTo(DWARF); // assertion succeeds: assertThat(frodo).satisfiesAnyOf(isElf, isHobbit, isDwarf); // assertion fails: TolkienCharacter boromir = new TolkienCharacter("Boromir", MAN); assertThat(boromir).satisfiesAnyOf(isHobbit, isElf, isDwarf);- Parameters:
assertions- the group of assertions to run against the object under test - must not be null.- Returns:
- this assertion object.
- Throws:
IllegalArgumentException- if any given assertions group is null- Since:
- 3.12.0
-
satisfiesAnyOf
Verifies that the actual object under test satisfies at least one of the given assertions group expressed asThrowingConsumers.This allows users to perform OR like assertions since only one the assertions group has to be met.
This is the same assertion as
satisfiesAnyOf(Consumer...)but the given consumers can throw checked exceptions.
More precisely,RuntimeExceptionandAssertionErrorare rethrown as they are andThrowablewrapped in aRuntimeException.Overriding error messageis not supported as it would prevent from getting the error messages of the failing assertions, these are valuable to figure out what went wrong.
Describing the assertion is supported (for example withDescriptable.as(String, Object...)).Example:
// read() throws IOException ThrowingConsumer<Reader> hasReachedEOF = reader -> assertThat(reader.read()).isEqualTo(-1); ThrowingConsumer<Reader> startsWithZ = reader -> assertThat(reader.read()).isEqualTo('Z'); // assertion succeeds as the file is empty (note that if hasReachedEOF was declared as a Consumer<Reader> the following line would not compile): assertThat(new FileReader("empty.txt")).satisfiesAnyOf(hasReachedEOF, startsWithZ); // alphabet.txt contains: abcdefghijklmnopqrstuvwxyz // assertion fails as alphabet.txt is not empty and starts with 'a': assertThat(new FileReader("alphabet.txt")).satisfiesAnyOf(hasReachedEOF, startsWithZ);- Parameters:
assertions- the group of assertions to run against the object under test - must not be null.- Returns:
- this assertion object.
- Throws:
IllegalArgumentException- if any given assertions group is nullRuntimeException- rethrown as is by the givenThrowingConsumeror wrapping anyThrowable.AssertionError- rethrown as is by the givenThrowingConsumer- Since:
- 3.21.0
-
satisfiesAnyOfForProxy
protected SELF satisfiesAnyOfForProxy(Consumer<? super ACTUAL>[] assertionsGroups) throws AssertionError - Throws:
AssertionError
-
setCustomRepresentation
-
setPrintAssertionsDescription
public static void setPrintAssertionsDescription(boolean printAssertionsDescription) -
setDescriptionConsumer
-
hasSameHashCodeAs
Verifies that the actual object has the same hashCode as the given object.Example:
// assertions succeed assertThat(42L).hasSameHashCodeAs(42L); assertThat("The Force").hasSameHashCodeAs("The Force"); assertThat(new Jedi("Yoda", "Blue")).hasSameHashCodeAs(new Jedi("Yoda", "Blue")); // assertions fail assertThat(42L).hasSameHashCodeAs(2501L); assertThat(null).hasSameHashCodeAs("The Force"); assertThat("The Force").hasSameHashCodeAs("Awakens");- Specified by:
hasSameHashCodeAsin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
other- the object to check hashCode against.- Returns:
- this assertion object.
-
doesNotHaveSameHashCodeAs
Verifies that the actual object does not have the same hashCode as the given object.Example:
// assertions succeed assertThat(42L).doesNotHaveSameHashCodeAs(2501L); assertThat("The Force").doesNotHaveSameHashCodeAs("Awakens"); // assertions fail assertThat(42L).doesNotHaveSameHashCodeAs(42L); assertThat("The Force").doesNotHaveSameHashCodeAs("The Force"); assertThat(new Jedi("Yoda", "Blue")).doesNotHaveSameHashCodeAs(new Jedi("Yoda", "Blue"));- Specified by:
doesNotHaveSameHashCodeAsin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>, ACTUAL> - Parameters:
other- the object to check hashCode against.- Returns:
- this assertion object.
-
newListAssertInstance
protected <E> AbstractListAssert<?,List<? extends E>, newListAssertInstanceE, ObjectAssert<E>> (List<? extends E> newActual) Create aAbstractListAssertfrom the given list.this method avoids code duplication when features like extracting/asList need to create a new list assertions.
- Type Parameters:
E- the type of elements.- Parameters:
newActual- new list under test- Returns:
- a new
AbstractListAssert.
-
usingRecursiveComparison
protected RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) -
usingRecursiveComparison
-
usingRecursiveAssertion
protected RecursiveAssertionAssert usingRecursiveAssertion(RecursiveAssertionConfiguration recursiveAssertionConfiguration) -
usingRecursiveAssertion
-
extracting
protected <ASSERT extends AbstractAssert<?,?>> ASSERT extracting(String propertyOrField, AssertFactory<Object, ASSERT> assertFactory) Extracts the value of given field/property from the object under test and creates a new assertion object using the given assert factory.If the object under test is a
Map, thepropertyOrFieldparameter is used as a key to the map.Nested field/property is supported, specifying "address.street.number" is equivalent to get the value corresponding to actual.getAddress().getStreet().getNumber()
Private field can be extracted unless you call
Assertions.setAllowExtractingPrivateFields(false).- Type Parameters:
ASSERT- the type of the resultingAssert- Parameters:
propertyOrField- the property/field to extract from the initial object under testassertFactory- the factory for the creation of the newAssert- Returns:
- the new
Assertinstance - Throws:
AssertionError- ifactualisnull- Since:
- 3.16.0
- See Also:
-
extracting
protected <T,ASSERT extends AbstractAssert<?, ASSERT extracting?>> (Function<? super ACTUAL, ? extends T> extractor, AssertFactory<T, ASSERT> assertFactory) Uses the givenFunctionto extract a value from the object under test and creates a new assertion object using the given assert factory.- Type Parameters:
T- the expected extracted value typeASSERT- the type of the resultingAssert- Parameters:
extractor- the extractor function used to extract the value from the object under testassertFactory- the factory for the creation of the newAssert- Returns:
- the new
Assertinstance - Throws:
AssertionError- ifactualisnull- Since:
- 3.16.0
- See Also:
-
areEqual
Deprecated.ComparisonStrategywill become part of the public API in the next major release and this method will be removed.Returns true if actual and other are equal according to the current comparison strategy.- Parameters:
actual- the object to compare to otherother- the object to compare to actual- Returns:
- true if actual and other are equal according to the underlying comparison strategy.
- Since:
- 3.23.0
-
actual
Returns actual (the object currently under test).This can be useful if after chaining assertions, the object under test has changed and you want to get it.
Examples of method changing actual:
extracting(Function)or a navigation methods likerootCause().Example:
TolkienCharacter frodo = TolkienCharacter.of("Frodo", 33, HOBBIT); String newActual = assertThat(frodo).extracting(TolkienCharacter::getName).actual(); // newActual == frodo.getName() assertThat(newActual).isSameAs(frodo.name);- Returns:
- actual the object currently under test.
- Since:
- 3.27.0
-
ComparisonStrategywill become part of the public API in the next major release and this method will be removed.