Class AbstractAssert<SELF extends AbstractAssert<SELF,ACTUAL>,ACTUAL>
- java.lang.Object
-
- org.assertj.core.api.AbstractAssert<SELF,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:
AbstractBooleanAssert,AbstractCharSequenceAssert,AbstractClassAssert,AbstractCompletableFutureAssert,AbstractDateAssert,AbstractEnumerableAssert,AbstractFileAssert,AbstractFutureAssert,AbstractInputStreamAssert,AbstractIterableAssert,AbstractObjectArrayAssert,AbstractObjectAssert,AbstractOptionalAssert,AbstractOptionalDoubleAssert,AbstractOptionalIntAssert,AbstractOptionalLongAssert,AbstractPredicateAssert,AbstractTemporalAssert,AbstractUriAssert,AbstractUrlAssert,AtomicBooleanAssert,AtomicIntegerAssert,AtomicLongAssert,AtomicReferenceArrayAssert,AtomicReferenceAssert,DoublePredicateAssert,IntPredicateAssert,LongPredicateAssert,ThrowableAssertAlternative
public abstract class AbstractAssert<SELF extends AbstractAssert<SELF,ACTUAL>,ACTUAL> extends Object implements Assert<SELF,ACTUAL>
Base class for all assertions.- Author:
- Alex Ruiz, Joel Costigliola, Mikhail Mazursky, Nicolas François
-
-
Constructor Summary
Constructors Constructor Description AbstractAssert(ACTUAL actual, Class<?> selfType)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description SELFas(String description, Object... args)Sets the description of the assertion that is going to be called after.SELFas(Description description)Sets the description of the assertion that is going to be called after.AbstractListAssert<?,List<?>,Object,ObjectAssert<Object>>asList()Verifies that the actual value is an instance of List, and returns a list assertion, to allow chaining of list-specific assertions from this call.AbstractCharSequenceAssert<?,String>asString()Verifies that the actual value is an instance of String, and returns a String assertion, to allow chaining of String-specific assertions from this call.SELFdescribedAs(String description, Object... args)Sets the description of the assertion that is going to be called after.SELFdescribedAs(Description description)Sets the description of the assertion that is going to be called after.StringdescriptionText()The description of this assertion set withdescribedAs(String, Object...)ordescribedAs(Description).SELFdoesNotHave(Condition<? super ACTUAL> condition)Verifies that the actual value does not satisfy the given condition.SELFdoesNotHaveSameClassAs(Object other)Verifies that the actual value does not have the same class as the given object.booleanequals(Object obj)Deprecated.useisEqualTo(java.lang.Object)insteadprotected voidfailWithMessage(String errorMessage, Object... arguments)Utility method to ease writing custom assertions classes usingString.format(String, Object...)specifiers in error message.WritableAssertionInfogetWritableAssertionInfo()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.SELFhas(Condition<? super ACTUAL> condition)Verifies that the actual value satisfies the given condition.inthashCode()Always returns 1.SELFhasSameClassAs(Object other)Verifies that the actual value has the same class as the given object.SELFhasToString(String expectedToString)Verifies that actualactual.toString()is equal to the givenString.protected SELFinBinary()Use binary object representation instead of standard representation in error messages.protected SELFinHexadecimal()Use hexadecimal object representation instead of standard representation in error messages.SELFis(Condition<? super ACTUAL> condition)Verifies that the actual value satisfies the given condition.SELFisEqualTo(Object expected)Verifies that the actual value is equal to the given one.SELFisExactlyInstanceOf(Class<?> type)Verifies that the actual value is exactly an instance of the given type.SELFisIn(Iterable<?> values)Verifies that the actual value is present in the given values.SELFisIn(Object... values)Verifies that the actual value is present in the given array of values.SELFisInstanceOf(Class<?> type)Verifies that the actual value is an instance of the given type.SELFisInstanceOfAny(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.SELFisNot(Condition<? super ACTUAL> condition)Verifies that the actual value does not satisfy the given condition.SELFisNotEqualTo(Object other)Verifies that the actual value is not equal to the given one.SELFisNotExactlyInstanceOf(Class<?> type)Verifies that the actual value is not exactly an instance of given type.SELFisNotIn(Iterable<?> values)Verifies that the actual value is not present in the given values.SELFisNotIn(Object... values)Verifies that the actual value is not present in the given array of values.SELFisNotInstanceOf(Class<?> type)Verifies that the actual value is not an instance of the given type.SELFisNotInstanceOfAny(Class<?>... types)Verifies that the actual value is not an instance of any of the given types.SELFisNotNull()Verifies that the actual value is notnull.SELFisNotOfAnyClassIn(Class<?>... types)Verifies that the actual value type is not in given types.SELFisNotSameAs(Object other)Verifies that the actual value is not the same as the given one, ie using == comparison.voidisNull()Verifies that the actual value isnull.SELFisOfAnyClassIn(Class<?>... types)Verifies that the actual value type is in given types.SELFisSameAs(Object expected)Verifies that the actual value is the same as the given one, ie using == comparison.SELFmatches(Predicate<? super ACTUAL> predicate)Verifies that the actual object matches the given predicate.SELFmatches(Predicate<? super ACTUAL> predicate, String predicateDescription)Verifies that the actual object matches the given predicate, the predicate description is used to get an informative error message.SELFoverridingErrorMessage(String newErrorMessage, Object... args)Overrides AssertJ default error message by the given one.SELFsatisfies(Consumer<ACTUAL> requirements)Verifies that the actual object satisfied the given requirements expressed as aConsumer.static voidsetCustomRepresentation(Representation customRepresentation)protected voidthrowAssertionError(ErrorMessageFactory errorMessageFactory)Utility method to throw anAssertionErrorgiven aBasicErrorMessageFactory.SELFusingComparator(Comparator<? super ACTUAL> customComparator)Use given custom comparator instead of relying on actual type A equals method for incoming assertion checks.SELFusingDefaultComparator()Revert to standard comparison for incoming assertion checks.SELFwithFailMessage(String newErrorMessage, Object... args)Alternative method foroverridingErrorMessage(java.lang.String, java.lang.Object...)SELFwithRepresentation(Representation representation)Use the givenRepresentationto describe/represent values in AssertJ error messages.SELFwithThreadDumpOnError()In case of an assertion error, a thread dump will be printed toSystem.err.
-
-
-
Field Detail
-
info
public final WritableAssertionInfo info
-
actual
protected final ACTUAL actual
-
myself
protected final SELF extends AbstractAssert<SELF,ACTUAL> myself
-
-
Method Detail
-
getWritableAssertionInfo
public WritableAssertionInfo 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
protected void failWithMessage(String errorMessage, Object... arguments)
Utility method to ease writing custom assertions classes usingString.format(String, Object...)specifiers in error message.Moreover, this method honors any description set with
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.
-
throwAssertionError
protected void throwAssertionError(ErrorMessageFactory errorMessageFactory)
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.
-
as
public SELF as(String description, Object... args)
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.
The description follows
String.format(String, Object...)syntax.Example :
try { // set a bad age to Mr Frodo which is really 33 years old. frodo.setAge(50); // specify a test description (call as() before the assertion !), it supports String format syntax. assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33); } catch (AssertionError e) { assertThat(e).hasMessage("[check Frodo's age] expected:<[33]> but was:<[50]>"); }- Specified by:
asin interfaceDescriptable<SELF extends AbstractAssert<SELF,ACTUAL>>- Parameters:
description- the new description to set.args- optional parameter if description is a format String.- Returns:
thisobject.- See Also:
Descriptable.describedAs(String, Object...)
-
as
public SELF as(Description description)
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:
asin interfaceDescriptable<SELF extends AbstractAssert<SELF,ACTUAL>>- Parameters:
description- the new description to set.- Returns:
thisobject.- See Also:
Descriptable.describedAs(Description)
-
inHexadecimal
protected SELF 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:
With Hexadecimal message:assertThat("µµµ").contains("μμμ"); java.lang.AssertionError: Expecting: <"µµµ"> to contain: <"μμμ">assertThat("µµµ").inHexadecimal().contains("μμμ"); java.lang.AssertionError: Expecting: <"['00B5', '00B5', '00B5']"> to contain: <"['03BC', '03BC', '03BC']">- Returns:
thisassertion object.
-
inBinary
protected SELF 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
public SELF describedAs(String description, Object... args)
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.
Alias for
since "as" is a keyword in Groovy.Descriptable.as(String, Object...)- Specified by:
describedAsin interfaceDescriptable<SELF extends AbstractAssert<SELF,ACTUAL>>- Parameters:
description- the new description to set.- Returns:
thisobject.
-
describedAs
public SELF describedAs(Description description)
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
public SELF isEqualTo(Object expected)
Verifies that the actual value is equal to the given one.Example:
// assertions will pass assertThat("abc").isEqualTo("abc"); assertThat(new HashMap<String, Integer>()).isEqualTo(new HashMap<String, Integer>()); // assertions will fail assertThat("abc").isEqualTo("123"); assertThat(new ArrayList<String>()).isEqualTo(1);
-
isNotEqualTo
public SELF isNotEqualTo(Object other)
Verifies that the actual value is not equal to the given one.Example:
// assertions will pass assertThat("abc").isNotEqualTo("123"); assertThat(new ArrayList<String>()).isNotEqualTo(1); // assertions will 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 will pass assertThat(value).isNull(); // assertions will fail assertThat("abc").isNull(); assertThat(new HashMap<String, Integer>()).isNull();
-
isNotNull
public SELF isNotNull()
Verifies that the actual value is notnull.Example:
// assertion will pass assertThat("abc").isNotNull(); assertThat(new HashMap<String, Integer>()).isNotNull(); // assertion will fail String value = null; assertThat(value).isNotNull();
-
isSameAs
public SELF isSameAs(Object expected)
Verifies that the actual value is the same as the given one, ie 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
public SELF isNotSameAs(Object other)
Verifies that the actual value is not the same as the given one, ie 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
public SELF isIn(Object... values)
Verifies that the actual value is present in the given array of values.Example:
Ring[] elvesRings = new Ring[] { vilya, nenya, narya }; // assertion will pass: assertThat(nenya).isIn(elvesRings); // assertion will fail: assertThat(oneRing).isIn(elvesRings);
-
isNotIn
public SELF isNotIn(Object... values)
Verifies that the actual value is not present in the given array of values.Example:
Ring[] elvesRings = new Ring[] { vilya, nenya, narya }; // assertion will pass: assertThat(oneRing).isNotIn(elvesRings); // assertion will fail: assertThat(nenya).isNotIn(elvesRings);
-
isIn
public SELF isIn(Iterable<?> values)
Verifies that the actual value is present in the given values.Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass: assertThat(nenya).isIn(elvesRings); // assertion will fail: assertThat(oneRing).isIn(elvesRings);
-
isNotIn
public SELF isNotIn(Iterable<?> values)
Verifies that the actual value is not present in the given values.Example:
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya); // assertion will pass: assertThat(oneRing).isNotIn(elvesRings); // assertion will fail: assertThat(nenya).isNotIn(elvesRings);
-
is
public SELF is(Condition<? super ACTUAL> condition)
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:
ExtensionPoints.is(Condition)
-
isNot
public SELF isNot(Condition<? super ACTUAL> condition)
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:
ExtensionPoints.isNot(Condition)
-
has
public SELF has(Condition<? super ACTUAL> condition)
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:
ExtensionPoints.is(Condition)
-
doesNotHave
public SELF doesNotHave(Condition<? super ACTUAL> condition)
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:
ExtensionPoints.isNot(Condition)
-
isInstanceOf
public SELF isInstanceOf(Class<?> type)
Verifies that the actual value is an instance of the given type.Example:
// assertions will pass assertThat("abc").isInstanceOf(String.class); assertThat(new HashMap<String, Integer>()).isInstanceOf(HashMap.class); assertThat(new HashMap<String, Integer>()).isInstanceOf(Map.class); // assertions will 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
public <T> SELF isInstanceOfSatisfying(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.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>- Parameters:
type- the type to check the actual value against.- Returns:
- this assertion object.
-
isInstanceOfAny
public SELF isInstanceOfAny(Class<?>... types)
Verifies that the actual value is an instance of any of the given types.Example:
// assertions will pass 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 will 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
public SELF isNotInstanceOf(Class<?> type)
Verifies that the actual value is not an instance of the given type.Example:
// assertions will pass assertThat(1).isNotInstanceOf(Double.class); assertThat(new ArrayList<String>()).isNotInstanceOf(LinkedList.class); // assertions will 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
public SELF isNotInstanceOfAny(Class<?>... types)
Verifies that the actual value is not an instance of any of the given types.Example:
// assertions will pass assertThat(1).isNotInstanceOfAny(Double.class, Float.class); assertThat(new ArrayList<String>()).isNotInstanceOfAny(LinkedList.class, Vector.class); // assertions will 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
public SELF hasSameClassAs(Object other)
Verifies that the actual value has the same class as the given object.Example:
// assertions will pass assertThat(1).hasSameClassAs(2); assertThat("abc").hasSameClassAs("123"); assertThat(new ArrayList<String>()).hasSameClassAs(new ArrayList<Integer>()); // assertions will 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
public SELF hasToString(String expectedToString)
Verifies that actualactual.toString()is equal to the givenString.Example :
CartoonCaracter homer = new CartoonCaracter("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.
-
doesNotHaveSameClassAs
public SELF doesNotHaveSameClassAs(Object other)
Verifies that the actual value does not have the same class as the given object.Example:
// assertions will pass assertThat(1).doesNotHaveSameClassAs("abc"); assertThat(new ArrayList<String>()).doesNotHaveSameClassAs(new LinkedList<String>()); // assertions will 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
public SELF isExactlyInstanceOf(Class<?> type)
Verifies that the actual value is exactly an instance of the given type.Example:
// assertions will pass assertThat("abc").isExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isExactlyInstanceOf(ArrayList.class); assertThat(new HashMap<String, Integer>()).isExactlyInstanceOf(HashMap.class); // assertions will 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
public SELF isNotExactlyInstanceOf(Class<?> type)
Verifies that the actual value is not exactly an instance of given type.Example:
// assertions will pass assertThat(1).isNotExactlyInstanceOf(String.class); assertThat(new ArrayList<String>()).isNotExactlyInstanceOf(List.class); assertThat(new HashMap<String, Integer>()).isNotExactlyInstanceOf(Map.class); // assertions will 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
public SELF isOfAnyClassIn(Class<?>... types)
Verifies that the actual value type is in given types.Example:
// assertions will pass assertThat(new HashMap<String, Integer>()).isOfAnyClassIn(HashMap.class, TreeMap.class); assertThat(new ArrayList<String>()).isOfAnyClassIn(ArrayList.class, LinkedList.class); // assertions will 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
public SELF isNotOfAnyClassIn(Class<?>... types)
Verifies that the actual value type is not in given types.Example:
// assertions will pass assertThat(new HashMap<String, Integer>()).isNotOfAnyClassIn(Map.class, TreeMap.class); assertThat(new ArrayList<String>()).isNotOfAnyClassIn(LinkedList.class, List.class); // assertions will 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
public AbstractListAssert<?,List<?>,Object,ObjectAssert<Object>> asList()
Verifies 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 will pass assertThat(sortedListAsObject).asList().isSorted(); Object unsortedListAsObject = Arrays.asList(3, 1, 2); // assertion will fail assertThat(unsortedListAsObject).asList().isSorted();
-
asString
public AbstractCharSequenceAssert<?,String> asString()
Verifies that the actual value is an instance of String, and returns a String assertion, to allow chaining of String-specific assertions from this call.Example :
Object stringAsObject = "hello world"; // assertion will pass assertThat(stringAsObject).asString().contains("hello"); // assertion will fail assertThat(stringAsObject).asString().contains("holla");
-
descriptionText
public String descriptionText()
The description of this assertion set withdescribedAs(String, Object...)ordescribedAs(Description).- Returns:
- the description String representation of this assertion.
-
overridingErrorMessage
public SELF overridingErrorMessage(String newErrorMessage, Object... args)
Overrides AssertJ default error message by the given one.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.
- Throws:
Exception- seeString.format(String, Object...)exception clause.
-
withFailMessage
public SELF withFailMessage(String newErrorMessage, Object... args)
Alternative method foroverridingErrorMessage(java.lang.String, java.lang.Object...)- 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.
- Throws:
Exception- seeString.format(String, Object...)exception clause.
-
usingComparator
public SELF usingComparator(Comparator<? super ACTUAL> customComparator)
Use given custom comparator instead of relying on actual type A equals method for incoming assertion checks.Custom comparator is bound to assertion instance, meaning that if a new assertion is created, it will use default comparison strategy. 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 incoming assertion checks.- Returns:
thisassertion object.
-
usingDefaultComparator
public SELF usingDefaultComparator()
Revert to standard comparison for incoming assertion checks.This method should be used to disable a custom comparison strategy set by calling
Assert.usingComparator(Comparator).- Specified by:
usingDefaultComparatorin interfaceAssert<SELF extends AbstractAssert<SELF,ACTUAL>,ACTUAL>- Returns:
thisassertion object.
-
withThreadDumpOnError
public SELF withThreadDumpOnError()
In case of an assertion error, a thread dump will be printed toSystem.err.Example :
will print a thread dump, something similar to this:assertThat("Messi").withThreadDumpOnError().isEqualTo("Ronaldo");"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
public SELF withRepresentation(Representation representation)
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 public boolean equals(Object obj)
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.
-
matches
public SELF matches(Predicate<? super ACTUAL> predicate)
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- if the actual does not match the givenPredicate.NullPointerException- if givenPredicateis null.
-
matches
public SELF matches(Predicate<? super ACTUAL> predicate, String predicateDescription)
Verifies that the actual object matches the given predicate, the predicate description is used to get an informative error message.Example :
The error message contains the predicate description, if the previous assertion fails, it will be:assertThat(player).matches(p -> p.isRookie(), "is rookie");Expecting: <player> to match 'is rookie' predicate.- Parameters:
predicate- thePredicateto matchpredicateDescription- a description of thePredicateused in the error message- Returns:
thisassertion object.- Throws:
AssertionError- if the actual does not match the givenPredicate.NullPointerException- if givenPredicateis null.NullPointerException- if given predicateDescription is null.
-
satisfies
public SELF satisfies(Consumer<ACTUAL> requirements)
Verifies that the actual object satisfied the given requirements expressed as aConsumer.This is useful to perform a group of assertions on a single object.
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> jediRequirements = jedi -> { assertThat(jedi.getLightSaberColor()).isEqualTo("Green"); assertThat(jedi.getName()).doesNotContain("Dark"); }; // assertions succeed: assertThat(yoda).satisfies(jediRequirements); assertThat(luke).satisfies(jediRequirements); // assertions fails: Jedi vader = new Jedi("Vader", "Red"); assertThat(vader).satisfies(jediRequirements);In the following example,
satisfiesprevents the need of 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); assertThat(stats.assistsPerGame).isGreaterThan(7.2); 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 given Consumer is null
-
setCustomRepresentation
public static void setCustomRepresentation(Representation customRepresentation)
-
-