Deprecated API
Contents
-
ClassDescriptionFor Android compatible assertions use the latest assertj 2.x version which is based on Java 7 only.
Assertions compatible with Android. Duplicated from
Assertions
.For Android compatible assertions use the latest assertj 2.x version which is based on Java 7 only.Android-compatible BDD-style assertions duplicated from
BDDAssertions
.For Android compatible assertions use the latest assertj 2.x version which is based on Java 7 only.BDD-style Android-compatible soft assertions. Duplicated from
BDDSoftAssertions
.For Android compatible assertions use the latest assertj 2.x version which is based on Java 7 only.Duplicate of
JUnitBDDSoftAssertions
compatible with Android.For Android compatible assertions use the latest assertj 2.x version which is based on Java 7 only.JUnitSoftAssertions rule compatible with Android. Duplicated from
JUnitSoftAssertions
.For Android compatible assertions use the latest assertj 2.x version which is based on Java 7 only.Soft assertions compatible with Android. Duplicated from
SoftAssertions
.This functionality (and more) has been rolled intoSoftAssertionsExtension
as of AssertJ 3.18.0.useSoftAssertionsExtension
instead. Same asSoftAssertions
, but with the following differences:
First, it's a JUnit Jupiter extension, which can be used without having to callassertAll()
, example:
Second, the failures are recognized by IDE's (like IntelliJ IDEA) which open a comparison window.public class SoftlyTest { @RegisterExtension public final JUnitJupiterBDDSoftAssertions softly = new JUnitJupiterBDDSoftAssertions(); @Test public void soft_bdd_assertions() throws Exception { softly.then(1).isEqualTo(2); softly.then(Lists.newArrayList(1, 2)).containsOnly(1, 2); } }
useSoftAssertionsExtension
instead. Same asSoftAssertions
, but with the following differences:
First, it's a JUnit Jupiter extension, which can be used without having to callassertAll()
, example:
Second, the failures are recognized by IDE's (like IntelliJ IDEA) which open a comparison window.public class SoftlyTest { @RegisterExtension public final JUnitJupiterSoftAssertions softly = new JUnitJupiterSoftAssertions(); @Test public void testSoftly() throws Exception { softly.assertThat(1).isEqualTo(2); softly.assertThat(Lists.newArrayList(1, 2)).containsOnly(1, 2); } }
useAssertionErrorMessagesAggregator
instead
-
MethodDescription
ComparisonStrategy
will become part of the public API in the next major release and this method will be removed.useasInstanceOf(InstanceOfAssertFactories.LIST)
insteaduseAbstractAssert.isEqualTo(java.lang.Object)
insteadCustom element Comparator is not supported for Boolean array comparison.Custom element Comparator is not supported for Boolean array comparison.Custom Comparator is not supported for Boolean comparison.Custom Comparator is not supported for Boolean comparison.useAbstractByteArrayAssert.asBase64Encoded()
instead.Encodes the actual array into a Base64 string, the encoded string becoming the new object under test.
Examples:
// assertion succeeds assertThat("AssertJ".getBytes()).encodedAsBase64().isEqualTo("QXNzZXJ0Sg==");
UseAbstractCharSequenceAssert.isBlank()
instead.UseAbstractCharSequenceAssert.isNotBlank()
instead.This assertion has some limitations, for example it does not handle tab vs space and would fail if elements are the same but in a different order.
The recommended approach is XML Unit which is able to deal with these limitations and provides many more features like XPath support and schema validation.Original javadoc:
Verifies that the actual
CharSequence
is equal to the given XMLCharSequence
after both have been formatted the same way.Example:
String expectedXml = "<rings>\n" + " <bearer>\n" + " <name>Frodo</name>\n" + " <ring>\n" + " <name>one ring</name>\n" + " <createdBy>Sauron</createdBy>\n" + " </ring>\n" + " </bearer>\n" + "</rings>"; // No matter how your xml string is formatted, isXmlEqualTo is able to compare it's content with another xml String. String oneLineXml = "<rings><bearer><name>Frodo</name><ring><name>one ring</name><createdBy>Sauron</createdBy></ring></bearer></rings>"; assertThat(oneLineXml).isXmlEqualTo(expectedXml); String xmlWithNewLine = "<rings>\n" + "<bearer> \n" + " <name>Frodo</name>\n" + " <ring>\n" + " <name>one ring</name>\n" + " <createdBy>Sauron</createdBy>\n" + " </ring>\n" + "</bearer>\n" + "</rings>"; assertThat(xmlWithNewLine).isXmlEqualTo(expectedXml); // You can compare it with oneLineXml assertThat(xmlWithNewLine).isXmlEqualTo(oneLineXml); // Tip : use isXmlEqualToContentOf assertion to compare your XML String with the content of an XML file : assertThat(oneLineXml).isXmlEqualToContentOf(new File("src/test/resources/formatted.xml"));
Custom element Comparator is not supported for CharSequence comparison.Custom element Comparator is not supported for CharSequence comparison.useAbstractClassAssert.hasPublicFields(String...)
instead.Combine isCompletedExceptionally with isNotCancelled instead:
This assertion is deprecated to change the semantics of failed to correspond toassertThat(future).isCompletedExceptionally() .isNotCancelled();
CompletableFuture.get()
failing.Original javadoc
Verifies that the
CompletableFuture
has completed exceptionally but has not been cancelled, this assertion is equivalent to:assertThat(future).isCompletedExceptionally() .isNotCancelled();
Assertion will pass :
Assertion will fail :CompletableFuture future = new CompletableFuture(); future.completeExceptionally(new RuntimeException()); assertThat(future).hasFailed();
CompletableFuture future = new CompletableFuture(); future.cancel(true); assertThat(future).hasFailed();
Although not 100% the same, consider using
AbstractCompletableFutureAssert.failsWithin(Duration)
orAbstractCompletableFutureAssert.failsWithin(long, TimeUnit)
instead:
This assertion is deprecated because it relies onCompletableFuture future = new CompletableFuture(); future.completeExceptionally(new RuntimeException("boom!")); assertThat(future).failsWithin(1, TimeUnit.SECONDS) .withThrowableOfType(RuntimeException.class) .withMessage("boom!");
AbstractCompletableFutureAssert.hasFailed()
semantics which we want to move away from (they are not clear!) and to use failure semantics corresponding toCompletableFuture.get()
failing.Original javadoc
Verifies that the
CompletableFuture
has completed exceptionally and returns a Throwable assertion object allowing to check the Throwable that has caused the future to fail.Assertion will pass :
Assertion will fail :CompletableFuture future = new CompletableFuture(); future.completeExceptionally(new RuntimeException("boom!")); assertThat(future).hasFailedWithThrowableThat().isInstanceOf(RuntimeException.class); .hasMessage("boom!");
CompletableFuture future = new CompletableFuture(); future.completeExceptionally(new RuntimeException()); assertThat(future).hasFailedWithThrowableThat().isInstanceOf(IllegalArgumentException.class);
Use matches with the following combination instead:
This assertion is deprecated because its semantic is not obvious.assertThat(future).matches (f -> f.isNotCompletedExceptionally() || f.isCancelled());
Original javadoc
Verifies that the
CompletableFuture
has not failed i.e: incomplete, completed or cancelled.
This is different fromAbstractCompletableFutureAssert.isNotCompletedExceptionally()
as a cancelled future has not failed but is completed exceptionally.Assertion will pass :
Assertion will fail :CompletableFuture future = new CompletableFuture(); future.cancel(true); assertThat(future).hasNotFailed();
CompletableFuture future = new CompletableFuture(); future.completeExceptionally(new RuntimeException()); assertThat(future).hasNotFailed();
prefer callingAbstractDateAssert.isAfterOrEqualTo(String)
prefer callingAbstractDateAssert.isAfterOrEqualTo(Date)
prefer callingAbstractDateAssert.isBeforeOrEqualTo(String)
prefer callingAbstractDateAssert.isBeforeOrEqualTo(Date)
UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Instant, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Instant, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Instant, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Instant, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractDateAssert.isCloseTo(Date, long)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.useAbstractDateAssert.hasDayOfMonth(int)
instead.useAbstractDateAssert.hasDayOfWeek(int)
instead.useAbstractDateAssert.hasHourOfDay(int)
instead.useAbstractDateAssert.hasMillisecond(int)
instead.useAbstractDateAssert.hasMinute(int)
instead.useAbstractDateAssert.hasMonth(int)
instead.useAbstractDateAssert.hasSecond(int)
instead.useAbstractDateAssert.hasYear(int)
instead.useAbstractFileAssert.hasSameTextualContentAs(File)
insteaduseAbstractFileAssert.hasSameTextualContentAs(File)
instead.Verifies that the content of the actual
File
is equal to the content of the given one. The charset to use when reading the actual file can be provided withAbstractFileAssert.usingCharset(Charset)
orAbstractFileAssert.usingCharset(String)
prior to calling this method; if not, the platform's default charset (as returned byCharset.defaultCharset()
) will be used. Examples:// use the default charset File xFile = Files.write(Paths.get("xfile.txt"), "The Truth Is Out There".getBytes()).toFile(); File xFileClone = Files.write(Paths.get("xfile-clone.txt"), "The Truth Is Out There".getBytes()).toFile(); File xFileFrench = Files.write(Paths.get("xfile-french.txt"), "La Vérité Est Ailleurs".getBytes()).toFile(); // use UTF-8 charset File xFileUTF8 = Files.write(Paths.get("xfile-clone.txt"), Arrays.asList("The Truth Is Out There"), StandardCharsets.UTF_8).toFile(); // The following assertion succeeds (default charset is used): assertThat(xFile).hasSameContentAs(xFileClone); // The following assertion succeeds (UTF-8 charset is used to read xFile): assertThat(xFileUTF8).usingCharset("UTF-8").hasSameContentAs(xFileClone); // The following assertion fails: assertThat(xFile).hasSameContentAs(xFileFrench);
useAbstractIterableAssert.singleElement()
insteadThis method is used withAbstractIterableAssert.usingFieldByFieldElementComparator()
which is deprecated in favor ofAbstractIterableAssert.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)
orAbstractIterableAssert.usingRecursiveComparison()
.When using
AbstractIterableAssert.usingRecursiveComparison()
the equivalent is:RecursiveComparisonAssert.withEqualsForFields(java.util.function.BiPredicate, String...)
RecursiveComparisonAssert.withComparatorForFields(Comparator, String...)
and when using
RecursiveComparisonConfiguration
:This method is used withAbstractIterableAssert.usingFieldByFieldElementComparator()
which is deprecated in favor ofAbstractIterableAssert.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)
orAbstractIterableAssert.usingRecursiveComparison()
.When using
AbstractIterableAssert.usingRecursiveComparison()
the equivalent is:RecursiveComparisonAssert.withEqualsForType(java.util.function.BiPredicate, Class)
RecursiveComparisonAssert.withComparatorForType(Comparator, Class)
and when using
RecursiveComparisonConfiguration
:This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAbstractIterableAssert.usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...)
instead.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonThis method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAbstractIterableAssert.usingRecursiveFieldByFieldElementComparatorOnFields(String...)
instead.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonThis method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAbstractIterableAssert.usingRecursiveFieldByFieldElementComparator()
orAbstractIterableAssert.usingRecursiveComparison()
instead to perform a true recursive comparison.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonUseAbstractLocalDateTimeAssert.isCloseTo(LocalDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractLocalDateTimeAssert.isCloseTo(LocalDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractLocalDateTimeAssert.isCloseTo(LocalDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractLocalTimeAssert.isCloseTo(LocalTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractLocalTimeAssert.isCloseTo(LocalTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.useAbstractMapAssert.extractingByKey(Object)
insteaduseAbstractMapAssert.extractingByKeys(Object[])
insteadCustom element Comparator is not supported for MapEntry comparison.Custom element Comparator is not supported for MapEntry comparison.This method is used withAbstractObjectArrayAssert.usingFieldByFieldElementComparator()
which is deprecated in favor ofAbstractObjectArrayAssert.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)
orAbstractObjectArrayAssert.usingRecursiveComparison()
.When using
AbstractObjectArrayAssert.usingRecursiveComparison()
the equivalent is:RecursiveComparisonAssert.withEqualsForFields(java.util.function.BiPredicate, String...)
RecursiveComparisonAssert.withComparatorForFields(Comparator, String...)
and when using
RecursiveComparisonConfiguration
:This method is used withAbstractObjectArrayAssert.usingFieldByFieldElementComparator()
which is deprecated in favor ofAbstractObjectArrayAssert.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)
orAbstractObjectArrayAssert.usingRecursiveComparison()
.When using
AbstractObjectArrayAssert.usingRecursiveComparison()
the equivalent is:RecursiveComparisonAssert.withEqualsForType(java.util.function.BiPredicate, Class)
RecursiveComparisonAssert.withComparatorForType(Comparator, Class)
and when using
RecursiveComparisonConfiguration
:This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAbstractObjectArrayAssert.usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...)
instead.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonThis method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAbstractObjectArrayAssert.usingRecursiveFieldByFieldElementComparatorOnFields(String...)
instead.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonThis method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAbstractObjectArrayAssert.usingRecursiveFieldByFieldElementComparator()
orAbstractObjectArrayAssert.usingRecursiveComparison()
instead to perform a true recursive comparison.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonUse the recursive comparison by callingAbstractObjectAssert.usingRecursiveComparison()
.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);
Prefer callingAbstractObjectAssert.usingRecursiveComparison()
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...)
andAbstractObjectAssert.usingComparatorForType(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);
Use the recursive comparison by callingAbstractObjectAssert.usingRecursiveComparison()
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
Use the recursive comparison by callingAbstractObjectAssert.usingRecursiveComparison()
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
Use the recursive comparison by callingAbstractObjectAssert.usingRecursiveComparison()
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
UseAbstractOffsetDateTimeAssert.isCloseTo(OffsetDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractOffsetDateTimeAssert.isCloseTo(OffsetDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractOffsetDateTimeAssert.isCloseTo(OffsetDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractOffsetDateTimeAssert.isCloseTo(OffsetDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractOffsetTimeAssert.isCloseTo(OffsetTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractOffsetTimeAssert.isCloseTo(OffsetTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAbstractOptionalAssert.get()
chained withAbstractObjectAssert.usingRecursiveComparison()
instead.TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT); TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT); // frodo and frodoClone are equals when doing a field by field comparison. assertThat(Optional.of(frodo)).get().usingRecursiveComparison() .isEqualTo(frodoClone);
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonuseAbstractPathAssert.hasSameTextualContentAs(Path)
insteadVerifies that the content of the actual
Path
is the same as the given one (both paths must be a readable files). The charset to use when reading the actual path can be provided withAbstractPathAssert.usingCharset(Charset)
orAbstractPathAssert.usingCharset(String)
prior to calling this method; if not, the platform's default charset (as returned byCharset.defaultCharset()
) will be used. Examples:// use the default charset Path xFile = Files.write(Paths.get("xfile.txt"), "The Truth Is Out There".getBytes()); Path xFileUTF8 = Files.write(Paths.get("xfile-clone.txt"), "The Truth Is Out There".getBytes("UTF-8")); Path xFileClone = Files.write(Paths.get("xfile-clone.txt"), "The Truth Is Out There".getBytes()); Path xFileFrench = Files.write(Paths.get("xfile-french.txt"), "La Vérité Est Ailleurs".getBytes()); // The following assertion succeeds (default charset is used): assertThat(xFile).hasSameContentAs(xFileClone); // The following assertion succeeds (UTF-8 charset is used to read xFile): assertThat(xFileUTF8).usingCharset("UTF-8").hasContent(xFileClone); // The following assertion fails: assertThat(xFile).hasSameContentAs(xFileFrench);
useAbstractPathAssert.hasSameTextualContentAs(Path, Charset)
insteadVerifies that the content of the actual
Path
is the same as the expected one, the expectedPath
being read with the given charset while the charset used to read the actual path can be provided withAbstractPathAssert.usingCharset(Charset)
orAbstractPathAssert.usingCharset(String)
prior to calling this method; if not, the platform's default charset (as returned byCharset.defaultCharset()
) will be used.Examples:
Path fileUTF8Charset = Files.write(Paths.get("actual"), Collections.singleton("Gerçek"), StandardCharsets.UTF_8); Charset turkishCharset = Charset.forName("windows-1254"); Path fileTurkischCharset = Files.write(Paths.get("expected"), Collections.singleton("Gerçek"), turkishCharset); // The following assertion succeeds: assertThat(fileUTF8Charset).usingCharset(StandardCharsets.UTF_8).hasSameContentAs(fileTurkischCharset, turkishCharset); // The following assertion fails: assertThat(fileUTF8Charset).usingCharset(StandardCharsets.UTF_8).hasSameContentAs(fileTurkischCharset, StandardCharsets.UTF_8);
useAbstractStringAssert.asBase64Decoded()
instead.Decodes the actual value as a Base64 encoded string, the decoded bytes becoming the new array under test.
Examples:
// assertion succeeds assertThat("QXNzZXJ0Sg==").decodedAsBase64().containsExactly("AssertJ".getBytes()); // assertion succeeds even without padding as it is optional by specification assertThat("QXNzZXJ0Sg").decodedAsBase64().containsExactly("AssertJ".getBytes()); // assertion fails as it has invalid Base64 characters assertThat("inv@lid").decodedAsBase64();
useAbstractThrowableAssert.cause()
instead.Returns a new assertion object that uses the cause of the current Throwable as the actual Throwable under test.
Examples:
Throwable cause = new IllegalArgumentException("wrong amount 123"); Throwable exception = new Exception("boom!", cause); // typical use: assertThat(throwableWithMessage).getCause() .hasMessageStartingWith("wrong amount");
useAbstractThrowableAssert.rootCause()
instead.Returns a new assertion object that uses the root cause of the current Throwable as the actual Throwable under test.
Examples:
Throwable rootCause = new JdbcException("invalid query"); Throwable cause = new RuntimeException(rootCause); Throwable exception = new Exception("boom!", cause); // typical use: assertThat(throwableWithMessage).getRootCause() .hasMessageStartingWith("invalid");
UseAbstractZonedDateTimeAssert.isCloseTo(ZonedDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractZonedDateTimeAssert.isCloseTo(ZonedDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractZonedDateTimeAssert.isCloseTo(ZonedDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.UseAbstractZonedDateTimeAssert.isCloseTo(ZonedDateTime, TemporalOffset)
instead, although not exactly the same semantics, this is the right way to compare with a given precision.useasInstanceOf(InstanceOfAssertFactories.LIST)
insteadThrows
if called. It is easy to accidentally callUnsupportedOperationException
equals(Object)
instead of
.Assert.isEqualTo(Object)
Custom Comparator is not supported for Boolean comparison.Custom Comparator is not supported for Boolean comparison.This method is used withAtomicReferenceArrayAssert.usingFieldByFieldElementComparator()
which is deprecated in favor ofAtomicReferenceArrayAssert.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)
orAbstractAssert.usingRecursiveComparison()
.When using
AbstractAssert.usingRecursiveComparison()
the equivalent is:RecursiveComparisonAssert.withEqualsForFields(java.util.function.BiPredicate, String...)
RecursiveComparisonAssert.withComparatorForFields(Comparator, String...)
and when using
RecursiveComparisonConfiguration
:This method is used withAtomicReferenceArrayAssert.usingFieldByFieldElementComparator()
which is deprecated in favor ofAtomicReferenceArrayAssert.usingRecursiveFieldByFieldElementComparator(RecursiveComparisonConfiguration)
orAbstractAssert.usingRecursiveComparison()
.When using
AbstractAssert.usingRecursiveComparison()
the equivalent is:RecursiveComparisonAssert.withEqualsForType(java.util.function.BiPredicate, Class)
RecursiveComparisonAssert.withComparatorForType(Comparator, Class)
and when using
RecursiveComparisonConfiguration
:This method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAtomicReferenceArrayAssert.usingRecursiveFieldByFieldElementComparatorIgnoringFields(String...)
instead.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonThis method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAtomicReferenceArrayAssert.usingRecursiveFieldByFieldElementComparatorOnFields(String...)
instead.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonThis method is deprecated because it performs a shallow field by field comparison, i.e. elements are compared field by field but the fields are compared with equals, useAtomicReferenceArrayAssert.usingRecursiveFieldByFieldElementComparator()
orAbstractAssert.usingRecursiveComparison()
instead to perform a true recursive comparison.
See https://assertj.github.io/doc/#assertj-core-recursive-comparisonuseFieldLocation.exactlyMatches(String)
instead.useFieldLocation.exactlyMatches(String)
instead.use https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#forceDelete-java.io.File- insteadUse eitherTempDir
orTemporaryFolder
useCollections.emptyList()
instead.useStandardRepresentation.toStringOf(Map)
instead.useStandardRepresentation.toStringOf(Map)
instead.UseObjects.deepEquals(Object, Object)
instead.useObjects.requireNonNull(Object)
instead.useObjects.requireNonNull(Object, String)
instead.
-
ConstructorDescriptionuse
assertThat(actual.get())
orAtomicReferenceAssert.hasValueSatisfying(Consumer)
.