Class AbstractObjectAssert<SELF extends AbstractObjectAssert<SELF,ACTUAL>,ACTUAL>
- java.lang.Object
-
- org.assertj.core.api.AbstractAssert<SELF,ACTUAL>
-
- org.assertj.core.api.AbstractObjectAssert<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:
AbstractAtomicFieldUpdaterAssert
,AbstractAtomicReferenceAssert
,AbstractComparableAssert
,AbstractMapAssert
,AbstractThrowableAssert
,ObjectAssert
,ThrowableAssertAlternative
public abstract class AbstractObjectAssert<SELF extends AbstractObjectAssert<SELF,ACTUAL>,ACTUAL> extends AbstractAssert<SELF,ACTUAL>
Base class for all implementations of assertions forObject
s.- Author:
- Yvonne Wang, Alex Ruiz, Nicolas François, Mikhail Mazursky, Joel Costigliola, Libor Ondrusek
-
-
Field Summary
Fields Modifier and Type Field Description private Map<String,Comparator<?>>
comparatorByPropertyOrField
private org.assertj.core.internal.TypeComparators
comparatorByType
-
Fields inherited from class org.assertj.core.api.AbstractAssert
actual, assertionErrorCreator, conditions, customRepresentation, info, myself, objects, printAssertionsDescription, throwUnsupportedExceptionOnEquals
-
-
Constructor Summary
Constructors Constructor Description AbstractObjectAssert(ACTUAL actual, Class<?> selfType)
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description SELF
as(String description, Object... args)
Sets the description of the assertion that is going to be called after.SELF
as(Description description)
Sets the description of the assertion that is going to be called after.AbstractObjectAssert<?,?>
extracting(String propertyOrField)
Extracts the value of given field/property from the object under test, the extracted value becoming the new object under test.AbstractListAssert<?,List<?>,Object,ObjectAssert<Object>>
extracting(String... propertiesOrFields)
Extracts the values of given fields/properties from the object under test into a list, this new list becoming the object under test.<ASSERT extends AbstractAssert<?,?>>
ASSERTextracting(String propertyOrField, InstanceOfAssertFactory<?,ASSERT> assertFactory)
Extracts the value of given field/property from the object under test, the extracted value becoming the new object under test.AbstractListAssert<?,List<?>,Object,ObjectAssert<Object>>
extracting(Function<? super ACTUAL,?>... extractors)
Uses the givenFunction
s to extract the values from the object under test into a list, this new list becoming the object under test.<T> AbstractObjectAssert<?,T>
extracting(Function<? super ACTUAL,T> extractor)
Uses the givenFunction
to extract a value from the object under test, the extracted value becoming the new object under test.<T,ASSERT extends AbstractAssert<?,?>>
ASSERTextracting(Function<? super ACTUAL,T> extractor, InstanceOfAssertFactory<?,ASSERT> assertFactory)
Uses the givenFunction
to extract a value from the object under test, the extracted value becoming the new object under test.protected AbstractListAssert<?,List<?>,Object,ObjectAssert<Object>>
extractingForProxy(Function<? super ACTUAL,?>[] extractors)
protected org.assertj.core.internal.TypeComparators
getComparatorsByType()
SELF
hasAllNullFieldsOrProperties()
Asserts that the actual object has only null fields or properties.SELF
hasAllNullFieldsOrPropertiesExcept(String... propertiesOrFieldsToIgnore)
Asserts that the actual object has only null fields or properties except for the given ones (inherited ones are taken into account).SELF
hasFieldOrProperty(String name)
Asserts that the actual object has the specified field or property.SELF
hasFieldOrPropertyWithValue(String name, Object value)
Asserts that the actual object has the specified field or property with the given value.SELF
hasNoNullFieldsOrProperties()
Asserts that the actual object has no null fields or properties (inherited ones are taken into account).SELF
hasNoNullFieldsOrPropertiesExcept(String... propertiesOrFieldsToIgnore)
Asserts that the actual object has no null fields or properties except for the given ones (inherited ones are taken into account).SELF
hasOnlyFields(String... expectedFieldNames)
Asserts that the actual object has only the specified fields and nothing else.SELF
isEqualToComparingFieldByField(Object other)
Deprecated.Use the recursive comparison by callingusingRecursiveComparison()
.SELF
isEqualToComparingFieldByFieldRecursively(Object other)
Deprecated.Prefer callingusingRecursiveComparison()
for comparing objects field by field as it offers more flexibility, better reporting and an easier to use API.SELF
isEqualToComparingOnlyGivenFields(Object other, String... propertiesOrFieldsUsedInComparison)
Deprecated.Use the recursive comparison by callingusingRecursiveComparison()
and specify the fields to ignore.SELF
isEqualToIgnoringGivenFields(Object other, String... propertiesOrFieldsToIgnore)
Deprecated.Use the recursive comparison by callingusingRecursiveComparison()
and chain withignoringFields(String...)
.SELF
isEqualToIgnoringNullFields(Object other)
Deprecated.Use the recursive comparison by callingusingRecursiveComparison()
and chain withignoringExpectedNullFields()
.protected <T> AbstractObjectAssert<?,T>
newObjectAssert(T objectUnderTest)
<T> SELF
returns(T expected, Function<ACTUAL,T> from)
Verifies that the object under test returns the given expected value from the givenFunction
, a typical usage is to pass a method reference to assert object's property.<T> SELF
usingComparatorForFields(Comparator<T> comparator, String... propertiesOrFields)
Allows to set a specific comparator to compare properties or fields with the given names.<T> SELF
usingComparatorForType(Comparator<? super T> comparator, Class<T> type)
Allows to set a specific comparator to compare properties or fields with the given type.RecursiveComparisonAssert<?>
usingRecursiveComparison()
Enable using a recursive field by field comparison strategy when calling the chainedisEqualTo
assertion.RecursiveComparisonAssert<?>
usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration)
Same asusingRecursiveComparison()
but allows to specify your ownRecursiveComparisonConfiguration
.(package private) SELF
withAssertionState(AbstractAssert assertInstance)
(package private) SELF
withComparatorByPropertyOrField(Map<String,Comparator<?>> comparatorsToPropaget)
(package private) SELF
withTypeComparator(org.assertj.core.internal.TypeComparators comparatorsByType)
-
Methods inherited from class org.assertj.core.api.AbstractAssert
asInstanceOf, asList, assertionError, asString, describedAs, descriptionText, doesNotHave, doesNotHaveSameClassAs, doesNotHaveSameHashCodeAs, doesNotHaveToString, equals, extracting, extracting, failure, failureWithActualExpected, failWithActualExpectedAndMessage, failWithMessage, getWritableAssertionInfo, has, hashCode, hasSameClassAs, hasSameHashCodeAs, hasToString, inBinary, inHexadecimal, is, isElementOfCustomAssert, isEqualTo, isExactlyInstanceOf, isIn, isIn, isInstanceOf, isInstanceOfAny, isInstanceOfSatisfying, isNot, isNotEqualTo, isNotExactlyInstanceOf, isNotIn, isNotIn, isNotInstanceOf, isNotInstanceOfAny, isNotNull, isNotOfAnyClassIn, isNotSameAs, isNull, isOfAnyClassIn, isSameAs, matches, matches, newListAssertInstance, overridingErrorMessage, overridingErrorMessage, satisfies, satisfies, satisfies, satisfiesAnyOf, satisfiesAnyOf, satisfiesAnyOfForProxy, setCustomRepresentation, setDescriptionConsumer, setPrintAssertionsDescription, throwAssertionError, usingComparator, usingComparator, usingDefaultComparator, withFailMessage, withFailMessage, withRepresentation, withThreadDumpOnError
-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface org.assertj.core.api.Descriptable
as, describedAs
-
-
-
-
Field Detail
-
comparatorByPropertyOrField
private Map<String,Comparator<?>> comparatorByPropertyOrField
-
comparatorByType
private org.assertj.core.internal.TypeComparators comparatorByType
-
-
Method Detail
-
as
public SELF as(Description description)
Description copied from interface:Descriptable
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
String
by 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.- Parameters:
description
- the new description to set.- Returns:
this
object.- See Also:
Descriptable.describedAs(Description)
-
as
public SELF as(String description, Object... args)
Description copied from interface:Descriptable
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 an incorrect 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]\n expected: 33\n but was: 50"); }
- Parameters:
description
- the new description to set.args
- optional parameter if description is a format String.- Returns:
this
object.- See Also:
Descriptable.describedAs(String, Object...)
-
isEqualToIgnoringNullFields
@Deprecated public SELF isEqualToIgnoringNullFields(Object other)
Deprecated.Use the recursive comparison by callingusingRecursiveComparison()
and chain withignoringExpectedNullFields()
.This method is deprecated because it only compares the first level of fields while the recursive comparison traverses all fields recursively (only stopping at java types).
For example suppose actual and expected are of type A which has the following structure:
A |— B b | |— String s | |— C c | |— String s | |— Date d |— int i
isEqualToIgnoringNullFields
will compare actual and expectedA.b
andA.i
fields but not B fields (it calls B equals method instead comparing B fields).
The recursive comparison on the other hand will introspect B fields and then C fields and will compare actual and expected respective fields values, that is:A.i
,A.B.s
,A.B.C.s
andA.B.C.d
.Concretely instead of writing:
You should write:assertThat(actual).isEqualToIgnoringNullFields(expected);
assertThat(actual).usingRecursiveComparison() .ignoringExpectedNullFields() .isEqualTo(expected);
Note that the recursive comparison also allows to ignore actual's null fields with
ignoringActualNullFields()
. Original javadocAsserts that the actual object is equal to the given one by comparing actual's properties/fields with other's not null properties/fields only (including inherited ones).
It means that if an actual field is not null and the corresponding field in other is null, this field will be ignored in comparison, but the opposite will make assertion fail (null field in actual, not null in other) as the field is used in the performed comparison and the values differ.
Note that comparison is not recursive, if one of the field is an Object, it will be compared to the other field using its
equals
method.If an object has a field and a property with the same name, the property value will be used over the field.
Private fields are used in comparison but this can be disabled using
Assertions.setAllowComparingPrivateFields(boolean)
, if disabled only accessible fields values are compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.The objects to compare can be of different types but the properties/fields used in comparison must exist in both, for example if actual object has a name String field, it is expected other object to also have one.
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter mysteriousHobbit = new TolkienCharacter(null, 33, HOBBIT); // Null fields in other/expected object are ignored, the mysteriousHobbit has null name thus name is ignored assertThat(frodo).isEqualToIgnoringNullFields(mysteriousHobbit); // OK // ... but this is not reversible ! assertThat(mysteriousHobbit).isEqualToIgnoringNullFields(frodo); // FAIL
- Parameters:
other
- the object to compareactual
to.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the actual or other object isnull
.AssertionError
- if the actual and the given object are not lenient equals.IntrospectionError
- if one of actual's field to compare can't be found in the other object.
-
isEqualToComparingOnlyGivenFields
@Deprecated public SELF isEqualToComparingOnlyGivenFields(Object other, String... propertiesOrFieldsUsedInComparison)
Deprecated.Use the recursive comparison by callingusingRecursiveComparison()
and specify the fields to ignore.Warning: the recursive comparison does not provide a strictly equivalent feature, instead it provides several ways to ignore fields in the comparison
by specifying fields to ignore
, orfields by type
orfields matching regexes
. The idea being that it is best to compare as many fields as possible and only ignore the ones that are not relevant (for example generated ids).This method is deprecated because it only compares the first level of fields while the recursive comparison traverses all fields recursively (only stopping at java types).
For example suppose actual and expected are of type A which has the following structure:
A |— B b | |— String s | |— C c | |— String s | |— Date d |— int i
isEqualToComparingOnlyGivenFields
will compare actual and expectedA.b
andA.i
fields but not B fields (it calls B equals method instead comparing B fields).
The recursive comparison on the other hand will introspect B fields and then C fields and will compare actual and expected respective fields values, that is:A.i
,A.B.s
,A.B.C.s
andA.B.C.d
.Assuming actual has 4 fields f1, f2, f3, f4, instead of writing:
You should write:assertThat(actual).isEqualToComparingOnlyGivenFields(expected, f1, f2);
Original javadocassertThat(actual).usingRecursiveComparison() .ignoringFields(f3, f4) .isEqualTo(expected);
Asserts that the actual object is equal to the given one using a property/field by property/field comparison on the given properties/fields only (fields can be inherited fields or nested fields). This can be handy if
equals
implementation of objects to compare does not suit you.Note that comparison is not recursive, if one of the field is an Object, it will be compared to the other field using its
equals
method.If an object has a field and a property with the same name, the property value will be used over the field.
Private fields are used in comparison but this can be disabled using
Assertions.setAllowComparingPrivateFields(boolean)
, if disabled only accessible fields values are compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.The objects to compare can be of different types but the properties/fields used in comparison must exist in both, for example if actual object has a name String field, it is expected the other object to also have one.
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT); // frodo and sam both are hobbits, so they are equals when comparing only race assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "race"); // OK // they are also equals when comparing only race name (nested field). assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "race.name"); // OK // ... but not when comparing both name and race assertThat(frodo).isEqualToComparingOnlyGivenFields(sam, "name", "race"); // FAIL
- Parameters:
other
- the object to compareactual
to.propertiesOrFieldsUsedInComparison
- properties/fields used in comparison.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the actual or other isnull
.AssertionError
- if the actual and the given objects are not equals property/field by property/field on given fields.IntrospectionError
- if one of actual's property/field to compare can't be found in the other object.IntrospectionError
- if a property/field does not exist in actual.
-
isEqualToIgnoringGivenFields
@Deprecated public SELF isEqualToIgnoringGivenFields(Object other, String... propertiesOrFieldsToIgnore)
Deprecated.Use the recursive comparison by callingusingRecursiveComparison()
and chain withignoringFields(String...)
.This method is deprecated because it only compares the first level of fields while the recursive comparison traverses all fields recursively (only stopping at java types).
For example suppose actual and expected are of type A which has the following structure:
A |— B b | |— String s | |— C c | |— String s | |— Date d |— int i
isEqualToIgnoringGivenFields
will compare actual and expectedA.b
andA.i
fields but not B fields (it calls B equals method instead comparing B fields).
The recursive comparison on the other hand will introspect B fields and then C fields and will compare actual and expected respective fields values, that is:A.i
,A.B.s
,A.B.C.s
andA.B.C.d
.Concretely instead of writing:
You should write:assertThat(actual).isEqualToIgnoringGivenFields(expected, "i", "b.s");
assertThat(actual).usingRecursiveComparison() .ignoringFields("i", "b.s") .isEqualTo(expected);
Note that the recursive comparison also allows to ignore fields
by type
ormatching regexes
. Original javadocAsserts that the actual object is equal to the given one by comparing their properties/fields except for the given ones (inherited ones are taken into account). This can be handy if
equals
implementation of objects to compare does not suit you.Note that comparison is not recursive, if one of the property/field is an Object, it will be compared to the other field using its
equals
method.If an object has a field and a property with the same name, the property value will be used over the field.
Private fields are used in comparison but this can be disabled using
Assertions.setAllowComparingPrivateFields(boolean)
, if disabled only accessible fields values are compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.The objects to compare can be of different types but the properties/fields used in comparison must exist in both, for example if actual object has a name String field, it is expected the other object to also have one.
Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter sam = new TolkienCharacter("Sam", 38, HOBBIT); // frodo and sam are equals when ignoring name and age since the only remaining field is race which they share as HOBBIT. assertThat(frodo).isEqualToIgnoringGivenFields(sam, "name", "age"); // OK // ... but they are not equals if only age is ignored as their names differ. assertThat(frodo).isEqualToIgnoringGivenFields(sam, "age"); // FAIL
- Parameters:
other
- the object to compareactual
to.propertiesOrFieldsToIgnore
- ignored properties/fields to ignore in comparison.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the actual or given object isnull
.AssertionError
- if the actual and the given objects are not equals property/field by property/field after ignoring given fields.IntrospectionError
- if one of actual's property/field to compare can't be found in the other object.
-
hasNoNullFieldsOrProperties
public SELF hasNoNullFieldsOrProperties()
Asserts that the actual object has no null fields or properties (inherited ones are taken into account).If an object has a field and a property with the same name, the property value will be used over the field.
Private fields are checked, but this can be disabled using
Assertions.setAllowComparingPrivateFields(boolean)
, if disabled only accessible fields values are checked, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter sam = new TolkienCharacter("Sam", 38, null); // assertion succeeds since all frodo's fields are set assertThat(frodo).hasNoNullFieldsOrProperties(); // assertion fails because sam does not have its race set assertThat(sam).hasNoNullFieldsOrProperties();
- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual object isnull
.AssertionError
- if some fields or properties of the actual object are null.- Since:
- 2.5.0 / 3.5.0
-
hasAllNullFieldsOrProperties
public SELF hasAllNullFieldsOrProperties()
Asserts that the actual object has only null fields or properties.If an object has a field and a property with the same name, the property value will be used over the field.
Private fields are checked, but this can be disable using
Assertions.setAllowComparingPrivateFields(boolean)
, if disable only accessible fields values are checked, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.Example:
TolkienCharacter frodo = new TolkienCharacter(null, null, null); TolkienCharacter sam = new TolkienCharacter("sam", null, null); // assertion succeeds since all frodo's fields are null assertThat(frodo).hasAllNullFieldsOrProperties(); // assertion fails because sam has its name set assertThat(sam).hasAllNullFieldsOrProperties();
- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual object isnull
.AssertionError
- if some field or properties of the actual object are not null.- Since:
- 3.12.0
-
hasNoNullFieldsOrPropertiesExcept
public SELF hasNoNullFieldsOrPropertiesExcept(String... propertiesOrFieldsToIgnore)
Asserts that the actual object has no null fields or properties except for the given ones (inherited ones are taken into account).If an object has a field and a property with the same name, the property value will be used over the field.
Private fields are checked, but this can be disabled using
Assertions.setAllowComparingPrivateFields(boolean)
, if disabled only accessible fields values are checked, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, null); // assertion succeeds since frodo has only null field is race assertThat(frodo).hasNoNullFieldsOrPropertiesExcept("race"); // ... but if we require the race field, the assertion fails assertThat(frodo).hasNoNullFieldsOrPropertiesExcept("name", "age");
- Parameters:
propertiesOrFieldsToIgnore
- properties/fields that won't be checked for null.- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual object isnull
.AssertionError
- if some (non ignored) fields or properties of the actual object are null.- Since:
- 2.5.0 / 3.5.0
-
hasAllNullFieldsOrPropertiesExcept
public SELF hasAllNullFieldsOrPropertiesExcept(String... propertiesOrFieldsToIgnore)
Asserts that the actual object has only null fields or properties except for the given ones (inherited ones are taken into account).If an object has a field and a property with the same name, the property value will be user over the field.
Private fields are checked, but this can be disable using
Assertions.setAllowComparingPrivateFields(boolean)
, if disabled only accessible fields values are checked, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.Example:
TolkienCharacter frodo = new TolkienCharacter("Frodo", null, null); // assertion succeeds since frodo has only non null field is name assertThat(frodo).hasAllNullFieldsOrPropertiesExcept("name"); // ... but if we specify any field other than name, the assertion fails assertThat(frodo).hasAllNullFieldsOrPropertiesExcept("race");
- Parameters:
propertiesOrFieldsToIgnore
- properties/fields that won't be checked for not being null.- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual object isnull
.AssertionError
- if some (non ignored) fields or properties of the actual object are not null.- Since:
- 3.12.0
-
isEqualToComparingFieldByField
@Deprecated public SELF isEqualToComparingFieldByField(Object other)
Deprecated.Use the recursive comparison by callingusingRecursiveComparison()
.This method is deprecated because it only compares the first level of fields while the recursive comparison traverses all fields recursively (only stopping at java types).
For example suppose actual and expected are of type A which has the following structure:
A |— B b | |— String s | |— C c | |— String s | |— Date d |— int i
isEqualToComparingFieldByField
will compare actual and expectedA.b
andA.i
fields but not B fields (it calls B equals method instead comparing B fields).
The recursive comparison on the other hand will introspect B fields and then C fields and will compare actual and expected respective fields values, that is:A.i
,A.B.s
,A.B.C.s
andA.B.C.d
.Concretely instead of writing:
You should write:assertThat(actual).isEqualToComparingFieldByField(expected);
Original javadocassertThat(actual).usingRecursiveComparison() .isEqualTo(expected);
Asserts that actual object is equal to the given object based on a property/field by property/field comparison (including inherited ones). This can be handy if
equals
implementation of objects to compare does not suit you.Note that comparison is not recursive, if one of the field is an Object, it will be compared to the other field using its
equals
method.If an object has a field and a property with the same name, the property value will be used over the field.
Private fields are used in comparison but this can be disabled using
Assertions.setAllowComparingPrivateFields(boolean)
, if disabled only accessible fields values are compared, accessible fields include directly accessible fields (e.g. public) or fields with an accessible getter.The objects to compare can be of different types but the properties/fields used in comparison must exist in both, for example if actual object has a name String field, it is expected the other object to also have one.
Example:
// equals not overridden in TolkienCharacter TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT); // Fail as equals compares object references assertThat(frodo).isEqualTo(frodoClone); // frodo and frodoClone are equals when doing a field by field comparison. assertThat(frodo).isEqualToComparingFieldByField(frodoClone);
- Parameters:
other
- the object to compareactual
to.- Returns:
this
assertions object- Throws:
AssertionError
- if the actual object isnull
.AssertionError
- if the actual and the given objects are not equals property/field by property/field.IntrospectionError
- if one of actual's property/field to compare can't be found in the other object.
-
getComparatorsByType
protected org.assertj.core.internal.TypeComparators getComparatorsByType()
-
usingComparatorForFields
public <T> SELF usingComparatorForFields(Comparator<T> comparator, String... propertiesOrFields)
Allows to set a specific comparator to compare properties or fields with the given names. A typical usage is for comparing double/float fields with a given precision.Comparators specified by this method have precedence over comparators added by
usingComparatorForType(java.util.Comparator<? super T>, java.lang.Class<T>)
.The comparators specified by this method are only used for field by field comparison like
isEqualToComparingFieldByField(Object)
.When used with
isEqualToComparingFieldByFieldRecursively(Object)
, the fields/properties must be specified from the root object, for example if Foo class as a Bar field and Bar class has an id, to set a comparator for Bar's id use"bar.id"
.Example:
public class TolkienCharacter { private String name; private double height; // constructor omitted } TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2); TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3); TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9); Comparator<Double> closeEnough = new Comparator<Double>() { double precision = 0.5; public int compare(Double d1, Double d2) { return Math.abs(d1 - d2) <= precision ? 0 : 1; } }; // assertions will pass assertThat(frodo).usingComparatorForFields(closeEnough, "height") .isEqualToComparingFieldByField(tallerFrodo); assertThat(frodo).usingComparatorForFields(closeEnough, "height") .isEqualToIgnoringNullFields(tallerFrodo); assertThat(frodo).usingComparatorForFields(closeEnough, "height") .isEqualToIgnoringGivenFields(tallerFrodo); assertThat(frodo).usingComparatorForFields(closeEnough, "height") .isEqualToComparingOnlyGivenFields(tallerFrodo); // assertion will fail assertThat(frodo).usingComparatorForFields(closeEnough, "height") .isEqualToComparingFieldByField(reallyTallFrodo);
- Type Parameters:
T
- the type of values to compare.- Parameters:
comparator
- theComparator
to usepropertiesOrFields
- the names of the properties and/or fields the comparator should be used for- Returns:
this
assertions object
-
usingComparatorForType
public <T> SELF usingComparatorForType(Comparator<? super T> comparator, Class<T> type)
Allows to set a specific comparator to compare properties or fields with the given type. A typical usage is for comparing fields of numeric type at a given precision.Comparators specified by
usingComparatorForFields(java.util.Comparator<T>, java.lang.String...)
have precedence over comparators specified by this method.The comparators specified by this method are only used for field by field comparison like
isEqualToComparingFieldByField(Object)
.Example:
If multiple compatible comparators have been registered for a givenpublic class TolkienCharacter { private String name; private double height; // constructor omitted } TolkienCharacter frodo = new TolkienCharacter("Frodo", 1.2); TolkienCharacter tallerFrodo = new TolkienCharacter("Frodo", 1.3); TolkienCharacter reallyTallFrodo = new TolkienCharacter("Frodo", 1.9); Comparator<Double> closeEnough = new Comparator<Double>() { double precision = 0.5; public int compare(Double d1, Double d2) { return Math.abs(d1 - d2) <= precision ? 0 : 1; } }; // assertions will pass assertThat(frodo).usingComparatorForType(closeEnough, Double.class) .isEqualToComparingFieldByField(tallerFrodo); assertThat(frodo).usingComparatorForType(closeEnough, Double.class) .isEqualToIgnoringNullFields(tallerFrodo); assertThat(frodo).usingComparatorForType(closeEnough, Double.class) .isEqualToIgnoringGivenFields(tallerFrodo); assertThat(frodo).usingComparatorForType(closeEnough, Double.class) .isEqualToComparingOnlyGivenFields(tallerFrodo); // assertion will fail assertThat(frodo).usingComparatorForType(closeEnough, Double.class) .isEqualToComparingFieldByField(reallyTallFrodo);
type
, the closest in the inheritance chain to the giventype
is chosen in the following order:- The comparator for the exact given
type
- The comparator of a superclass of the given
type
- The comparator of an interface implemented by the given
type
- Type Parameters:
T
- the type of objects that the comparator should be used for- Parameters:
comparator
- theComparator
to usetype
- theClass
of the type the comparator should be used for- Returns:
this
assertions object
- The comparator for the exact given
-
hasFieldOrProperty
public SELF hasFieldOrProperty(String name)
Asserts that the actual object has the specified field or property. Static and synthetic fields are ignored since 3.19.0.Private fields are matched by default but this can be changed by calling
Assertions.setAllowExtractingPrivateFields(false)
.Example:
public class TolkienCharacter { private String name; private int age; // constructor omitted public String getName() { return this.name; } } TolkienCharacter frodo = new TolkienCharacter("Frodo", 33); // assertions will pass : assertThat(frodo).hasFieldOrProperty("name") .hasFieldOrProperty("age"); // private field are matched by default // assertions will fail : assertThat(frodo).hasFieldOrProperty("not_exists"); assertThat(frodo).hasFieldOrProperty(null); // disable looking for private fields Assertions.setAllowExtractingPrivateFields(false); assertThat(frodo).hasFieldOrProperty("age");
- Parameters:
name
- the field/property name to check- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual object isnull
.IllegalArgumentException
- if name isnull
.AssertionError
- if the actual object does not have the given field/property
-
hasFieldOrPropertyWithValue
public SELF hasFieldOrPropertyWithValue(String name, Object value)
Asserts that the actual object has the specified field or property with the given value. Static and synthetic fields are ignored since 3.19.0.Private fields are matched by default but this can be changed by calling
Assertions.setAllowExtractingPrivateFields(false)
.If you are looking to chain multiple assertions on different properties in a type safe way, consider chaining
returns(Object, Function)
calls.Example:
public class TolkienCharacter { private String name; private int age; // constructor omitted public String getName() { return this.name; } } TolkienCharacter frodo = new TolkienCharacter("Frodo", 33); TolkienCharacter noname = new TolkienCharacter(null, 33); // assertions will pass : assertThat(frodo).hasFieldOrPropertyWithValue("name", "Frodo"); assertThat(frodo).hasFieldOrPropertyWithValue("age", 33); assertThat(noname).hasFieldOrPropertyWithValue("name", null); // assertions will fail : assertThat(frodo).hasFieldOrPropertyWithValue("name", "not_equals"); assertThat(frodo).hasFieldOrPropertyWithValue(null, 33); assertThat(frodo).hasFieldOrPropertyWithValue("age", null); assertThat(noname).hasFieldOrPropertyWithValue("name", "Frodo"); // disable extracting private fields Assertions.setAllowExtractingPrivateFields(false); assertThat(frodo).hasFieldOrPropertyWithValue("age", 33);
- Parameters:
name
- the field/property name to checkvalue
- the field/property expected value- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual object isnull
.IllegalArgumentException
- if name isnull
.AssertionError
- if the actual object does not have the given field/propertyAssertionError
- if the actual object has the given field/property but not with the expected value- See Also:
hasFieldOrProperty(java.lang.String)
-
hasOnlyFields
public SELF hasOnlyFields(String... expectedFieldNames)
Asserts that the actual object has only the specified fields and nothing else.The assertion only checks declared fields (inherited fields are not checked) that are not static or synthetic.
By default private fields are included in the check, this can be disabled with
Assertions.setAllowExtractingPrivateFields(false);
but be mindful this is has a global effect on all field introspection in AssertJ.Example:
public class TolkienCharacter { private String name; public int age; public String getName() { return this.name; } } TolkienCharacter frodo = new TolkienCharacter("Frodo", 33); // assertion succeeds: assertThat(frodo).hasOnlyFields("name", "age"); // assertions fail: assertThat(frodo).hasOnlyFields("name"); assertThat(frodo).hasOnlyFields("not_exists"); assertThat(frodo).hasOnlyFields(null);
- Parameters:
expectedFieldNames
- the expected field names actual should have- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual object isnull
.IllegalArgumentException
- if expectedFieldNames isnull
.AssertionError
- if the actual object does not have the expected fields (without extra ones)- Since:
- 3.19.0
-
extracting
public AbstractListAssert<?,List<?>,Object,ObjectAssert<Object>> extracting(String... propertiesOrFields)
Extracts the values of given fields/properties from the object under test into a list, this new list becoming the object under test.If you extract "id", "name" and "email" fields/properties then the list will contain the id, name and email values of the object under test, you can then perform list assertions on the extracted values.
If the object under test is a
Map
withString
keys, extracting will extract values matching the given fields/properties.Nested fields/properties are supported, specifying "adress.street.number" is equivalent to:
or if address is a// "adress.street.number" corresponding to pojo properties actual.getAdress().getStreet().getNumber();
Map
:// "adress" is a Map property (that is getAdress() returns a Map) actual.getAdress().get("street").getNumber();
Private fields can be extracted unless you call
Assertions.setAllowExtractingPrivateFields(false)
.Example:
A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked for, if the field is not accessible (i.e. does not exist) an// Create frodo, setting its name, age and Race (Race having a name property) TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); // let's verify Frodo's name, age and race name: assertThat(frodo).extracting("name", "age", "race.name") .containsExactly("Frodo", 33, "Hobbit");
IntrospectionError
is thrown.Note that the order of extracted values is consistent with the order of the given property/field.
- Parameters:
propertiesOrFields
- the properties/fields to extract from the initial object under test- Returns:
- a new assertion object whose object under test is the list containing the extracted properties/fields values
- Throws:
IntrospectionError
- if one of the given name does not match a field or property
-
extracting
public AbstractObjectAssert<?,?> extracting(String propertyOrField)
Extracts the value of given field/property from the object under test, the extracted value becoming the new object under test.If the object under test is a
Map
, thepropertyOrField
parameter is used as a key to the map.Nested fields/properties are supported, specifying "adress.street.number" is equivalent to:
or if address is a// "adress.street.number" corresponding to pojo properties actual.getAdress().getStreet().getNumber();
Map
:// "adress" is a Map property (that is getAdress() returns a Map) actual.getAdress().get("street").getNumber();
Private field can be extracted unless you call
Assertions.setAllowExtractingPrivateFields(false)
.Note that since the value is extracted as an Object, only Object assertions can be chained after extracting.
Example:
// Create frodo, setting its name, age and Race (Race having a name property) TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); // let's extract and verify Frodo's name: assertThat(frodo).extracting("name") .isEqualTo("Frodo"); // or its race name: assertThat(frodo).extracting("race.name") .isEqualTo("Hobbit"); // The extracted value being a String, we would like to use String assertions but we can't due to Java generics limitations. // The following assertion does NOT compile: assertThat(frodo).extracting("name") .startsWith("Fro"); // To get String assertions, use
extracting(String, InstanceOfAssertFactory)
: assertThat(frodo).extracting("name", as(InstanceOfAssertFactories.STRING)) .startsWith("Fro");A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked for, if the field is not accessible (i.e. does not exist) an
IntrospectionError
is thrown.- Parameters:
propertyOrField
- the property/field to extract from the initial object under test- Returns:
- a new
ObjectAssert
instance whose object under test is the extracted property/field value - Throws:
IntrospectionError
- if one of the given name does not match a field or property- Since:
- 3.13.0
- See Also:
extracting(String, InstanceOfAssertFactory)
-
extracting
public <ASSERT extends AbstractAssert<?,?>> ASSERT extracting(String propertyOrField, InstanceOfAssertFactory<?,ASSERT> assertFactory)
Extracts the value of given field/property from the object under test, the extracted value becoming the new object under test.If the object under test is a
Map
, thepropertyOrField
parameter 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)
.The
assertFactory
parameter allows to specify anInstanceOfAssertFactory
, which is used to get the assertions narrowed to the factory type.Wrapping the given
InstanceOfAssertFactory
withAssertions.as(InstanceOfAssertFactory)
makes the assertion more readable.Example:
// Create frodo, setting its name, age and Race (Race having a name property) TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); // let's extract and verify Frodo's name: assertThat(frodo).extracting("name", as(InstanceOfAssertFactories.STRING)) .startsWith("Fro"); // The following assertion will fail as Frodo's name is not an Integer: assertThat(frodo).extracting("name", as(InstanceOfAssertFactories.INTEGER)) .isZero();
A property with the given name is looked for first, if it doesn't exist then a field with the given name is looked for, if the field is not accessible (i.e. does not exist) an
IntrospectionError
is thrown.- Type Parameters:
ASSERT
- the type of the resultingAssert
- Parameters:
propertyOrField
- the property/field to extract from the initial object under testassertFactory
- the factory which verifies the type and creates the newAssert
- Returns:
- a new narrowed
Assert
instance whose object under test is the extracted property/field value - Throws:
NullPointerException
- if the given factory isnull
IntrospectionError
- if one of the given name does not match a field or property- Since:
- 3.14.0
-
extracting
@SafeVarargs public final AbstractListAssert<?,List<?>,Object,ObjectAssert<Object>> extracting(Function<? super ACTUAL,?>... extractors)
Uses the givenFunction
s to extract the values from the object under test into a list, this new list becoming the object under test.If the given
Function
s extract the id, name and email values then the list will contain the id, name and email values of the object under test, you can then perform list assertions on the extracted values.Example:
// Create frodo, setting its name, age and Race (Race having a name property) TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); // let's verify Frodo's name, age and race name: assertThat(frodo).extracting(TolkienCharacter::getName, character -> character.age, // public field character -> character.getRace().getName()) .containsExactly("Frodo", 33, "Hobbit");
Note that the order of extracted values is consistent with the order of given extractor functions.
- Parameters:
extractors
- the extractor functions to extract values from the Object under test.- Returns:
- a new assertion object whose object under test is the list containing the extracted values
-
extractingForProxy
protected AbstractListAssert<?,List<?>,Object,ObjectAssert<Object>> extractingForProxy(Function<? super ACTUAL,?>[] extractors)
-
extracting
public <T> AbstractObjectAssert<?,T> extracting(Function<? super ACTUAL,T> extractor)
Uses the givenFunction
to extract a value from the object under test, the extracted value becoming the new object under test.Note that since the value is extracted as an Object, only Object assertions can be chained after extracting.
Example:
// Create frodo, setting its name, age and Race TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); // let's extract and verify Frodo's name: assertThat(frodo).extracting(TolkienCharacter::getName) .isEqualTo("Frodo"); // The extracted value being a String, we would like to use String assertions but we can't due to Java generics limitations. // The following assertion does NOT compile: assertThat(frodo).extracting(TolkienCharacter::getName) .startsWith("Fro"); // To get String assertions, use
extracting(Function, InstanceOfAssertFactory)
: assertThat(frodo).extracting(TolkienCharacter::getName, as(InstanceOfAssertFactories.STRING)) .startsWith("Fro");- Type Parameters:
T
- the expected extracted value type.- Parameters:
extractor
- the extractor function used to extract the value from the object under test.- Returns:
- a new
ObjectAssert
instance whose object under test is the extracted value - Since:
- 3.11.0
- See Also:
extracting(Function, InstanceOfAssertFactory)
-
extracting
public <T,ASSERT extends AbstractAssert<?,?>> ASSERT extracting(Function<? super ACTUAL,T> extractor, InstanceOfAssertFactory<?,ASSERT> assertFactory)
Uses the givenFunction
to extract a value from the object under test, the extracted value becoming the new object under test.Note that since the value is extracted as an Object, only Object assertions can be chained after extracting.
The
assertFactory
parameter allows to specify anInstanceOfAssertFactory
, which is used to get the assertions narrowed to the factory type.Wrapping the given
InstanceOfAssertFactory
withAssertions.as(InstanceOfAssertFactory)
makes the assertion more readable.Example:
// Create frodo, setting its name, age and Race TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); // let's extract and verify Frodo's name: assertThat(frodo).extracting(TolkienCharacter::getName, as(InstanceOfAssertFactories.STRING)) .startsWith("Fro"); // The following assertion will fail as Frodo's name is not an Integer: assertThat(frodo).extracting(TolkienCharacter::getName, as(InstanceOfAssertFactories.INTEGER)) .isZero();
- 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 which verifies the type and creates the newAssert
- Returns:
- a new narrowed
Assert
instance whose object under test is the extracted value - Throws:
NullPointerException
- if the given factory isnull
- Since:
- 3.14.0
-
isEqualToComparingFieldByFieldRecursively
@Deprecated public SELF isEqualToComparingFieldByFieldRecursively(Object other)
Deprecated.Prefer callingusingRecursiveComparison()
for comparing objects field by field as it offers more flexibility, better reporting and an easier to use API. Asserts that the object under test (actual) is equal to the given object based on a recursive property/field by property/field comparison (including inherited ones). This can be useful if actual'sequals
implementation does not suit you. The recursive property/field comparison is not applied on fields having a customequals
implementation, i.e. the overriddenequals
method will be used instead of a field by field comparison.The recursive comparison handles cycles. By default
floats
are compared with a precision of 1.0E-6 anddoubles
with 1.0E-15.You can specify a custom comparator per (nested) fields or type with respectively
usingComparatorForFields(Comparator, String...)
andusingComparatorForType(Comparator, Class)
.The objects to compare can be of different types but must have the same properties/fields. For example if actual object has a name String field, it is expected the other object to also have one. If an object has a field and a property with the same name, the property value will be used over the field.
Example:
public class Person { public String name; public double height; public Home home = new Home(); public Person bestFriend; // constructor with name and height omitted for brevity } public class Home { public Address address = new Address(); } public static class Address { public int number = 1; } Person jack = new Person("Jack", 1.80); jack.home.address.number = 123; Person jackClone = new Person("Jack", 1.80); jackClone.home.address.number = 123; // cycle are handled in comparison jack.bestFriend = jackClone; jackClone.bestFriend = jack; // will fail as equals compares object references assertThat(jack).isEqualTo(jackClone); // jack and jackClone are equals when doing a recursive field by field comparison assertThat(jack).isEqualToComparingFieldByFieldRecursively(jackClone); // any type/field can be compared with a a specific comparator. // let's change jack's height a little bit jack.height = 1.81; // assertion fails because of the height difference // (the default precision comparison for double is 1.0E-15) assertThat(jack).isEqualToComparingFieldByFieldRecursively(jackClone); // this succeeds because we allow a 0.5 tolerance on double assertThat(jack).usingComparatorForType(new DoubleComparator(0.5), Double.class) .isEqualToComparingFieldByFieldRecursively(jackClone); // you can set a comparator on specific fields (nested fields are supported) assertThat(jack).usingComparatorForFields(new DoubleComparator(0.5), "height") .isEqualToComparingFieldByFieldRecursively(jackClone);
- Parameters:
other
- the object to compareactual
to.- Returns:
this
assertion object.- Throws:
AssertionError
- if the actual object isnull
.AssertionError
- if the actual and the given objects are not deeply equal property/field by property/field.IntrospectionError
- if one property/field to compare can not be found.
-
returns
public <T> SELF returns(T expected, Function<ACTUAL,T> from)
Verifies that the object under test returns the given expected value from the givenFunction
, a typical usage is to pass a method reference to assert object's property.Wrapping the given
Function
withAssertions.from(Function)
makes the assertion more readable.Example:
// from is not mandatory but it makes the assertions more readable assertThat(frodo).returns("Frodo", from(TolkienCharacter::getName)) .returns("Frodo", TolkienCharacter::getName) // no from :( .returns(HOBBIT, from(TolkienCharacter::getRace));
- Type Parameters:
T
- the expected value type the givenmethod
returns.- Parameters:
expected
- the value the object under test method's call should return.from
-Function
used to acquire the value to test from the object under test. Must not benull
- Returns:
this
assertion object.- Throws:
NullPointerException
- if givenfrom
function is null
-
usingRecursiveComparison
public RecursiveComparisonAssert<?> usingRecursiveComparison()
Enable using a recursive field by field comparison strategy when calling the chainedisEqualTo
assertion.The detailed documentation available here: https://assertj.github.io/doc/#assertj-core-recursive-comparison.
Example:
public class Person { String name; double height; Home home = new Home(); } public class Home { Address address = new Address(); Date ownedSince; } public static class Address { int number; String street; } Person sherlock = new Person("Sherlock", 1.80); sherlock.home.ownedSince = new Date(123); sherlock.home.address.street = "Baker Street"; sherlock.home.address.number = 221; Person sherlock2 = new Person("Sherlock", 1.80); sherlock2.home.ownedSince = new Date(123); sherlock2.home.address.street = "Baker Street"; sherlock2.home.address.number = 221; // assertion succeeds as the data of both objects are the same. assertThat(sherlock).usingRecursiveComparison() .isEqualTo(sherlock2); // assertion fails because sherlock.equals(sherlock2) is false. assertThat(sherlock).isEqualTo(sherlock2);
The recursive comparison is performed according to the default
RecursiveComparisonConfiguration
that is:- actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call
withStrictTypeChecking()
to change that behavior). - overridden equals methods were used in the comparison (unless stated otherwise)
- these types were compared with the following comparators:
- java.lang.Double -> DoubleComparator[precision=1.0E-15]
- java.lang.Float -> FloatComparator[precision=1.0E-6]
- any comparators previously registered with
usingComparatorForType(Comparator, Class)
It is possible to change the comparison behavior, among things what you can is:
- Choosing a strict or lenient recursive comparison (lenient being the default which allows to compare different types like
Book
andBookDto
- Ignoring fields in the comparison
- Specifying comparators to use in the comparison per fields and types
- Forcing recursive comparison on classes that have redefined equals (by default overridden equals are used)
Please consult the detailed documentation available here: https://assertj.github.io/doc/#assertj-core-recursive-comparison
- Overrides:
usingRecursiveComparison
in classAbstractAssert<SELF extends AbstractObjectAssert<SELF,ACTUAL>,ACTUAL>
- Returns:
- a new
RecursiveComparisonAssert
instance
- actual and expected objects and their fields were compared field by field recursively even if they were not of the same type, this allows for example to compare a Person to a PersonDto (call
-
usingRecursiveComparison
public RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration)
Same asusingRecursiveComparison()
but allows to specify your ownRecursiveComparisonConfiguration
.- Overrides:
usingRecursiveComparison
in classAbstractAssert<SELF extends AbstractObjectAssert<SELF,ACTUAL>,ACTUAL>
- Parameters:
recursiveComparisonConfiguration
- theRecursiveComparisonConfiguration
used in the chainedisEqualTo
assertion.- Returns:
- a new
RecursiveComparisonAssert
instance built with the givenRecursiveComparisonConfiguration
.
-
newObjectAssert
protected <T> AbstractObjectAssert<?,T> newObjectAssert(T objectUnderTest)
-
withAssertionState
SELF withAssertionState(AbstractAssert assertInstance)
- Overrides:
withAssertionState
in classAbstractAssert<SELF extends AbstractObjectAssert<SELF,ACTUAL>,ACTUAL>
-
withTypeComparator
SELF withTypeComparator(org.assertj.core.internal.TypeComparators comparatorsByType)
-
withComparatorByPropertyOrField
SELF withComparatorByPropertyOrField(Map<String,Comparator<?>> comparatorsToPropaget)
-
-