Top Description Fields Constructors Methods
org.assertj.core.api

public abstract Class AbstractOptionalAssert<SELF extends AbstractOptionalAssert<SELF, VALUE>, VALUE>

extends AbstractAssert<SELF extends AbstractOptionalAssert<SELF, VALUE>, Optional<VALUE>>
Class Inheritance
Known Direct Subclasses
org.assertj.core.api.OptionalAssert
Annotations
@SuppressWarnings:deprecation, RedundantSuppression
Type Parameters
<SELF>
the "self" type of this assertion class.
<VALUE>
type of the value contained in the java.util.Optional.
Static Imports
org.assertj.core.api.Assertions.assertThat, org.assertj.core.error.OptionalShouldBeEmpty.shouldBeEmpty, .OptionalShouldBePresent.shouldBePresent, .OptionalShouldContain.shouldContain, .OptionalShouldContain.shouldContainSame, .OptionalShouldContainInstanceOf.shouldContainInstanceOf, org.assertj.core.util.Preconditions.checkArgument

Assertions for java.util.Optional.
Authors
Jean-Christophe Gay, Nicolai Parlog, Grzegorz Piwowarek

Field Summary

Modifier and TypeField and Description
private ComparisonStrategy
Inherited from org.assertj.core.api.AbstractAssert:
actualassertionErrorCreatorconditionscustomRepresentationinfomyselfobjectsprintAssertionsDescriptionthrowUnsupportedExceptionOnEquals

Constructor Summary

AccessConstructor and Description
protected
AbstractOptionalAssert(Optional<VALUE> actual, Class<?> selfType)

Method Summary

Modifier and TypeMethod and Description
private void
private void
checkNotNull(Object expectedValue)

public SELF

Returns:

this assertion object.
contains
(VALUE
the expected value inside the java.util.Optional.
expectedValue
)

Verifies that the actual java.util.Optional contains the given value (alias of hasValue(Object)).

public SELF

Returns:

this assertion object.
containsInstanceOf
(Class<?>
the expected class of the value inside the Optional.
clazz
)

Verifies that the actual Optional contains a value that is an instance of the argument.

public SELF

Returns:

this assertion object.
containsSame
(VALUE
the expected value inside the java.util.Optional.
expectedValue
)

Verifies that the actual java.util.Optional contains the instance given as an argument (i.e. it must be the same instance).

public <
the type wrapped in the Optional after the flatMap operation.
U
>
AbstractOptionalAssert<?, U>

Returns:

a new AbstractOptionalAssert for assertions chaining on the flatMap of the Optional.
flatMap
(Function<? super VALUE, Optional<U>>
the Function to use in the flatMap operation.
mapper
)

Call flatMap on the Optional under test, assertions chained afterwards are performed on the Optional resulting from the flatMap call.

public AbstractObjectAssert<?, VALUE>

Returns:

a new AbstractObjectAssert for assertions chaining on the value of the Optional.
get
()

Verifies that the actual Optional is not null and not empty and returns an Object assertion that allows chaining (object) assertions on the optional value.

public <
the type of the resulting Assert
ASSERT extends AbstractAssert<?, ?>
>
ASSERT

Returns:

a new narrowed Assert instance for assertions chaining on the value of the Optional
get
(InstanceOfAssertFactory<?, ASSERT>
the factory which verifies the type and creates the new Assert
assertFactory
)

Verifies that the actual Optional is not null and not empty and returns an new assertion instance to chain assertions on the optional value.

public SELF

Returns:

this assertion object.
hasValue
(VALUE
the expected value inside the java.util.Optional.
expectedValue
)

Verifies that the actual java.util.Optional contains the given value (alias of contains(Object)).

public SELF

Returns:

this assertion object.
hasValueSatisfying
(Consumer<VALUE>
to further assert on the object contained inside the java.util.Optional.
requirement
)

Verifies that the actual java.util.Optional contains a value and gives this value to the given java.util.function.Consumer for further assertions.

public SELF

Returns:

this assertion object.
hasValueSatisfying
(Condition<? super VALUE>
the given condition.
condition
)

Verifies that the actual Optional contains a value which satisfies the given Condition.

private AbstractObjectAssert<?, VALUE>
public SELF

Returns:

this assertion object.
isEmpty
()

Verifies that the actual java.util.Optional is empty.

public SELF

Returns:

this assertion object.
isNotEmpty
()

Verifies that there is a value present in the actual java.util.Optional, it's an alias of isPresent().

public SELF

Returns:

this assertion object.
isNotPresent
()

Verifies that the actual java.util.Optional is empty (alias of isEmpty()).

public SELF

Returns:

this assertion object.
isPresent
()

Verifies that there is a value present in the actual java.util.Optional.

public <
the type wrapped in the Optional after the map operation.
U
>
AbstractOptionalAssert<?, U>

Returns:

a new AbstractOptionalAssert for assertions chaining on the map of the Optional.
map
(Function<? super VALUE, ? extends U>
the Function to use in the map operation.
mapper
)

Call map on the Optional under test, assertions chained afterwards are performed on the Optional resulting from the map call.

public SELF

Returns:

this assertion object.
usingDefaultValueComparator
()

Revert to standard comparison for incoming assertion Optional value checks.

public SELF

Returns:

this assertion object.
usingFieldByFieldValueComparator
()

Deprecated 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, use get() chained with AbstractObjectAssert#usingRecursiveComparison() instead.
Use field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type A equals method to compare the Optional value's object for incoming assertion checks.
public RecursiveAssertionAssert

Returns:

A new instance of RecursiveAssertionAssert built with a default RecursiveAssertionConfiguration.
usingRecursiveAssertion
()

Overrides org.assertj.core.api.AbstractAssert.usingRecursiveAssertion.

Asserts that the given predicate is met for all fields of the object under test recursively (but not the object itself).

public RecursiveAssertionAssert

Returns:

A new instance of RecursiveAssertionAssert built with a default RecursiveAssertionConfiguration.
usingRecursiveAssertion
(RecursiveAssertionConfiguration
The recursion configuration described above.
recursiveAssertionConfiguration
)

Overrides org.assertj.core.api.AbstractAssert.usingRecursiveAssertion.

The same as usingRecursiveAssertion(), but this method allows the developer to pass in an explicit recursion configuration.

public RecursiveComparisonAssert<?>

Returns:

a new RecursiveComparisonAssert instance
usingRecursiveComparison
()

Overrides org.assertj.core.api.AbstractAssert.usingRecursiveComparison.

Enable using a recursive field by field comparison strategy when calling the chained RecursiveComparisonAssert,

Example:

 public class Person {
  String name;
  boolean hasPhd;
}

public class Doctor {
 String name;
 boolean hasPhd;
}

Doctor drSheldon = new Doctor("Sheldon Cooper", true);
Person sheldon = new Person("Sheldon Cooper", true);

Optional<Doctor> doctor = Optional.of(drSheldon);
Optional<Person> person = Optional.of(sheldon);

// assertion succeeds as both maps contains equivalent items.
public RecursiveComparisonAssert<?>
public SELF

Returns:

this assertion object.
usingValueComparator
(Comparator<? super VALUE>
the comparator to use for incoming assertion checks.
customComparator
)

Use given custom comparator instead of relying on actual type A equals method to compare the Optional value's object for incoming assertion checks.

Inherited from org.assertj.core.api.AbstractAssert:
areEqualasInstanceOfasListassertionErrorasStringdescribedAsdescriptionTextdoesNotHavedoesNotHaveSameClassAsdoesNotHaveSameHashCodeAsdoesNotHaveToStringdoesNotHaveToStringequalsextractingextractingfailurefailureWithActualExpectedfailWithActualExpectedAndMessagefailWithMessagegetWritableAssertionInfohashashCodehasSameClassAshasSameHashCodeAshasToStringhasToStringinBinaryinHexadecimalisisElementOfCustomAssertisEqualToisExactlyInstanceOfisInisInisInstanceOfisInstanceOfAnyisInstanceOfSatisfyingisNotisNotEqualToisNotExactlyInstanceOfisNotInisNotInisNotInstanceOfisNotInstanceOfAnyisNotNullisNotOfAnyClassInisNotSameAsisNullisOfAnyClassInisSameAsmatchesmatchesnewListAssertInstanceoverridingErrorMessageoverridingErrorMessagesatisfiessatisfiessatisfiessatisfiesAnyOfsatisfiesAnyOfsatisfiesAnyOfForProxysatisfiesForProxysetCustomRepresentationsetDescriptionConsumersetPrintAssertionsDescriptionthrowAssertionErrorusingComparatorusingComparatorusingDefaultComparatorwithAssertionStatewithFailMessagewithFailMessagewithRepresentationwithThreadDumpOnError

Field Detail

optionalValueComparisonStrategyback to summary
private ComparisonStrategy optionalValueComparisonStrategy

Constructor Detail

AbstractOptionalAssertback to summary
protected AbstractOptionalAssert(Optional<VALUE> actual, Class<?> selfType)

Method Detail

assertValueIsPresentback to summary
private void assertValueIsPresent()
checkNotNullback to summary
private void checkNotNull(Object expectedValue)
containsback to summary
public SELF contains(VALUE expectedValue)

Verifies that the actual java.util.Optional contains the given value (alias of hasValue(Object)).

Assertion will pass :

 assertThat(Optional.of("something")).contains("something");
assertThat(Optional.of(10)).contains(10);
Assertion will fail :
 assertThat(Optional.of("something")).contains("something else");
assertThat(Optional.of(20)).contains(10);
Parameters
expectedValue:VALUE

the expected value inside the java.util.Optional.

Returns:SELF

this assertion object.

containsInstanceOfback to summary
public SELF containsInstanceOf(Class<?> clazz)

Verifies that the actual Optional contains a value that is an instance of the argument.

Assertions will pass:

 assertThat(Optional.of("something")).containsInstanceOf(String.class)
                                    .containsInstanceOf(Object.class);

assertThat(Optional.of(10)).containsInstanceOf(Integer.class);
Assertion will fail:
 assertThat(Optional.of("something")).containsInstanceOf(Integer.class);
Parameters
clazz:Class<?>

the expected class of the value inside the Optional.

Returns:SELF

this assertion object.

containsSameback to summary
public SELF containsSame(VALUE expectedValue)

Verifies that the actual java.util.Optional contains the instance given as an argument (i.e. it must be the same instance).

Assertion will pass :

 String someString = "something";
assertThat(Optional.of(someString)).containsSame(someString);

// Java will create the same 'Integer' instance when boxing small ints
assertThat(Optional.of(10)).containsSame(10);
Assertion will fail :
 // not even equal:
assertThat(Optional.of("something")).containsSame("something else");
assertThat(Optional.of(20)).containsSame(10);

// equal but not the same:
assertThat(Optional.of(new String("something"))).containsSame(new String("something"));
assertThat(Optional.of(new Integer(10))).containsSame(new Integer(10));
Parameters
expectedValue:VALUE

the expected value inside the java.util.Optional.

Returns:SELF

this assertion object.

flatMapback to summary
public <U> AbstractOptionalAssert<?, U> flatMap(Function<? super VALUE, Optional<U>> mapper)

Call flatMap on the Optional under test, assertions chained afterwards are performed on the Optional resulting from the flatMap call.

Examples:

 Function<String, Optional<String>> UPPER_CASE_OPTIONAL_STRING =
      s -> s == null ? Optional.empty() : Optional.of(s.toUpperCase());

// assertions succeed
assertThat(Optional.of("something")).contains("something")
                                    .flatMap(UPPER_CASE_OPTIONAL_STRING)
                                    .contains("SOMETHING");

assertThat(Optional.<String>empty()).flatMap(UPPER_CASE_OPTIONAL_STRING)
                                    .isEmpty();

assertThat(Optional.<String>ofNullable(null)).flatMap(UPPER_CASE_OPTIONAL_STRING)
                                             .isEmpty();

// assertion fails
assertThat(Optional.of("something")).flatMap(UPPER_CASE_OPTIONAL_STRING)
                                    .contains("something");
Parameters
<U>
the type wrapped in the Optional after the flatMap operation.
mapper:Function<? super VALUE, Optional<U>>

the Function to use in the flatMap operation.

Returns:AbstractOptionalAssert<?, U>

a new AbstractOptionalAssert for assertions chaining on the flatMap of the Optional.

Annotations
@CheckReturnValue
Exceptions
AssertionError:
if the actual Optional is null.
Since
3.6.0
getback to summary
public AbstractObjectAssert<?, VALUE> get()

Verifies that the actual Optional is not null and not empty and returns an Object assertion that allows chaining (object) assertions on the optional value.

Note that it is only possible to return Object assertions after calling this method due to java generics limitations.

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(Optional.of(frodo)).get().hasNoNullFieldsOrProperties();

// assertion does not succeed because sam does not have its race set
assertThat(Optional.of(sam)).get().hasNoNullFieldsOrProperties();
Returns:AbstractObjectAssert<?, VALUE>

a new AbstractObjectAssert for assertions chaining on the value of the Optional.

Annotations
@CheckReturnValue
Exceptions
AssertionError:
Since
3.9.0
See Also
get(InstanceOfAssertFactory)
getback to summary
public <ASSERT extends AbstractAssert<?, ?>> ASSERT get(InstanceOfAssertFactory<?, ASSERT> assertFactory)

Verifies that the actual Optional is not null and not empty and returns an new assertion instance to chain assertions on the optional value.

The assertFactory parameter allows to specify an InstanceOfAssertFactory, which is used to get the assertions narrowed to the factory type.

Wrapping the given InstanceOfAssertFactory with Assertions#as(InstanceOfAssertFactory) makes the assertion more readable.

Example:

 // assertion succeeds
assertThat(Optional.of("frodo")).get(as(InstanceOfAssertFactories.STRING)).startsWith("fro");

// assertion does not succeed because frodo is not an Integer
assertThat(Optional.of("frodo")).get(as(InstanceOfAssertFactories.INTEGER)).isZero();
Parameters
<ASSERT>
the type of the resulting Assert
assertFactory:InstanceOfAssertFactory<?, ASSERT>

the factory which verifies the type and creates the new Assert

Returns:ASSERT

a new narrowed Assert instance for assertions chaining on the value of the Optional

Annotations
@CheckReturnValue
Exceptions
NullPointerException:
if the given factory is null
AssertionError:
Since
3.14.0
hasValueback to summary
public SELF hasValue(VALUE expectedValue)

Verifies that the actual java.util.Optional contains the given value (alias of contains(Object)).

Assertion will pass :

 assertThat(Optional.of("something")).hasValue("something");
assertThat(Optional.of(10)).contains(10);
Assertion will fail :
 assertThat(Optional.of("something")).hasValue("something else");
assertThat(Optional.of(20)).contains(10);
Parameters
expectedValue:VALUE

the expected value inside the java.util.Optional.

Returns:SELF

this assertion object.

hasValueSatisfyingback to summary
public SELF hasValueSatisfying(Consumer<VALUE> requirement)

Verifies that the actual java.util.Optional contains a value and gives this value to the given java.util.function.Consumer for further assertions. Should be used as a way of deeper asserting on the containing object, as further requirement(s) for the value.

Assertions will pass :

 // one requirement
assertThat(Optional.of(10)).hasValueSatisfying(i -> { assertThat(i).isGreaterThan(9); });

// multiple requirements
assertThat(Optional.of(someString)).hasValueSatisfying(s -> {
  assertThat(s).isEqualTo("something");
  assertThat(s).startsWith("some");
  assertThat(s).endsWith("thing");
}); 
Assertions will fail :
 assertThat(Optional.of("something")).hasValueSatisfying(s -> {
    assertThat(s).isEqualTo("something else");
  });

// fail because optional is empty, there is no value to perform assertion on
assertThat(Optional.empty()).hasValueSatisfying(o -> {});
Parameters
requirement:Consumer<VALUE>

to further assert on the object contained inside the java.util.Optional.

Returns:SELF

this assertion object.

hasValueSatisfyingback to summary
public SELF hasValueSatisfying(Condition<? super VALUE> condition)

Verifies that the actual Optional contains a value which satisfies the given Condition.

Examples:

 Condition<TolkienCharacter> isAnElf = new Condition<>(character -> character.getRace() == ELF, "an elf");

TolkienCharacter legolas = new TolkienCharacter("Legolas", 1000, ELF);
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);

// assertion succeeds
assertThat(Optional.of(legolas)).hasValueSatisfying(isAnElf);

// assertion fails
assertThat(Optional.of(frodo)).hasValueSatisfying(isAnElf);
Parameters
condition:Condition<? super VALUE>

the given condition.

Returns:SELF

this assertion object.

Exceptions
AssertionError:
  • if the actual Optional is null or empty.
  • if the actual value does not satisfy the given condition.
NullPointerException:
if the given condition is null.
Since
3.6.0
internalGetback to summary
private AbstractObjectAssert<?, VALUE> internalGet()
isEmptyback to summary
public SELF isEmpty()

Verifies that the actual java.util.Optional is empty.

Assertion will pass :

 assertThat(Optional.empty()).isEmpty();
Assertion will fail :
 assertThat(Optional.of("something")).isEmpty();
Returns:SELF

this assertion object.

isNotEmptyback to summary
public SELF isNotEmpty()

Verifies that there is a value present in the actual java.util.Optional, it's an alias of isPresent().

Assertion will pass :

 assertThat(Optional.of("something")).isNotEmpty();
Assertion will fail :
 assertThat(Optional.empty()).isNotEmpty();
Returns:SELF

this assertion object.

isNotPresentback to summary
public SELF isNotPresent()

Verifies that the actual java.util.Optional is empty (alias of isEmpty()).

Assertion will pass :

 assertThat(Optional.empty()).isNotPresent();
Assertion will fail :
 assertThat(Optional.of("something")).isNotPresent();
Returns:SELF

this assertion object.

isPresentback to summary
public SELF isPresent()

Verifies that there is a value present in the actual java.util.Optional.

Assertion will pass :

 assertThat(Optional.of("something")).isPresent();
Assertion will fail :
 assertThat(Optional.empty()).isPresent();
Returns:SELF

this assertion object.

mapback to summary
public <U> AbstractOptionalAssert<?, U> map(Function<? super VALUE, ? extends U> mapper)

Call map on the Optional under test, assertions chained afterwards are performed on the Optional resulting from the map call.

Examples:

 // assertions succeed
assertThat(Optional.<String>empty()).map(String::length)
                                    .isEmpty();

assertThat(Optional.of("42")).contains("42")
                             .map(String::length)
                             .contains(2);

// assertion fails
assertThat(Optional.of("42")).map(String::length)
                             .contains(3);
Parameters
<U>
the type wrapped in the Optional after the map operation.
mapper:Function<? super VALUE, ? extends U>

the Function to use in the map operation.

Returns:AbstractOptionalAssert<?, U>

a new AbstractOptionalAssert for assertions chaining on the map of the Optional.

Annotations
@CheckReturnValue
Exceptions
AssertionError:
if the actual Optional is null.
Since
3.6.0
usingDefaultValueComparatorback to summary
public SELF usingDefaultValueComparator()

Revert to standard comparison for incoming assertion Optional value checks.

This method should be used to disable a custom comparison strategy set by calling usingValueComparator(Comparator).

Returns:SELF

this assertion object.

Annotations
@CheckReturnValue
usingFieldByFieldValueComparatorback to summary
public SELF usingFieldByFieldValueComparator()

Deprecated

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, use get() chained with AbstractObjectAssert#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-comparison

Use field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type A equals method to compare the Optional value's object for incoming assertion checks. Private fields are included but this can be disabled using Assertions#setAllowExtractingPrivateFields(boolean).

This can be handy if equals method of the Optional value's object to compare does not suit you.

Note that the comparison is not recursive, if one of the fields/properties is an Object, it will be compared to the other field/property using its equals method.

Example:

 TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);

// Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references
assertThat(Optional.of(frodo)).contains(frodoClone);

// frodo and frodoClone are equals when doing a field by field comparison.
assertThat(Optional.of(frodo)).usingFieldByFieldValueComparator().contains(frodoClone);
Returns:SELF

this assertion object.

Annotations
@Deprecated
@CheckReturnValue
@SuppressWarnings:DeprecatedIsStillUsed, deprecation
usingRecursiveAssertionback to summary
public RecursiveAssertionAssert usingRecursiveAssertion()

Overrides org.assertj.core.api.AbstractAssert.usingRecursiveAssertion.

Asserts that the given predicate is met for all fields of the object under test recursively (but not the object itself).

For example if the object under test is an instance of class A, A has a B field and B a C field then the assertion checks A's B field and B's C field and all C's fields.

The recursive algorithm employs cycle detection, so object graphs with cyclic references can safely be asserted over without causing looping.

This method enables recursive asserting using default configuration, which means all fields of all objects have the java.util.function.Predicate applied to them (including primitive fields), no fields are excluded, but:

You can change how the recursive assertion deals with arrays, collections, maps and optionals, see:

It is possible to assert several predicates over the object graph in a row.

The classes used in recursive asserting are not thread safe. Care must be taken when running tests in parallel not to run assertions over object graphs that are being shared between tests.

Example

 class Author {
  String name;
  String email;
  List<Book> books = new ArrayList<>();

  Author(String name, String email) {
    this.name = name;
    this.email = email;
  }
}

class Book {
  String title;
  Author[] authors;

  Book(String title, Author[] authors) {
    this.title = title;
    this.authors = authors;
  }
}

Author pramodSadalage = new Author("Pramod Sadalage", "[email protected]");
Author martinFowler = new Author("Martin Fowler", "[email protected]");
Author kentBeck = new Author("Kent Beck", "[email protected]");

Book noSqlDistilled = new Book("NoSql Distilled", new Author[] {pramodSadalage, martinFowler});
pramodSadalage.books.add(noSqlDistilled);
martinFowler.books.add(noSqlDistilled);

Book refactoring = new Book("Refactoring", new Author[] {martinFowler, kentBeck});
martinFowler.books.add(refactoring);
kentBeck.books.add(refactoring);

// assertion succeeds
assertThat(Optional.of(pramodSadalage)).usingRecursiveAssertion()
                                       .allFieldsSatisfy(field -> field != null); 

In case one or more fields in the object graph fails the predicate test, the entire assertion will fail. Failing fields will be listed in the failure report using a JSON path-ish notation.

Returns:RecursiveAssertionAssert

A new instance of RecursiveAssertionAssert built with a default RecursiveAssertionConfiguration.

Annotations
@Override
usingRecursiveAssertionback to summary
public RecursiveAssertionAssert usingRecursiveAssertion(RecursiveAssertionConfiguration recursiveAssertionConfiguration)

Overrides org.assertj.core.api.AbstractAssert.usingRecursiveAssertion.

The same as usingRecursiveAssertion(), but this method allows the developer to pass in an explicit recursion configuration. This configuration gives fine-grained control over what to include in the recursion, such as:

  • Exclusion of fields that are null
  • Exclusion of fields by path
  • Exclusion of fields by type
  • Exclusion of primitive fields
  • Inclusion of Java Class Library types in the recursive execution
  • Treatment of java.util.Collection and array objects
  • Treatment of java.util.Map objects
  • Treatment of Optional and primitive Optional objects

Please refer to the documentation of RecursiveAssertionConfiguration.Builder for more details.

Parameters
recursiveAssertionConfiguration:RecursiveAssertionConfiguration

The recursion configuration described above.

Returns:RecursiveAssertionAssert

A new instance of RecursiveAssertionAssert built with a default RecursiveAssertionConfiguration.

Annotations
@Override
usingRecursiveComparisonback to summary
public RecursiveComparisonAssert<?> usingRecursiveComparison()

Overrides org.assertj.core.api.AbstractAssert.usingRecursiveComparison.

Enable using a recursive field by field comparison strategy when calling the chained RecursiveComparisonAssert,

Example:

 public class Person {
  String name;
  boolean hasPhd;
}

public class Doctor {
 String name;
 boolean hasPhd;
}

Doctor drSheldon = new Doctor("Sheldon Cooper", true);
Person sheldon = new Person("Sheldon Cooper", true);

Optional<Doctor> doctor = Optional.of(drSheldon);
Optional<Person> person = Optional.of(sheldon);

// assertion succeeds as both maps contains equivalent items.
assertThat(doctor).usingRecursiveComparison()
                  .isEqualTo(person);

// assertion fails because leonard names are different.
drSheldon.setName("Sheldon Kooper");
assertThat(doctor).usingRecursiveComparison()
                  .isEqualTo(person);
A detailed documentation for the recursive comparison is available here: https://assertj.github.io/doc/#assertj-core-recursive-comparison.

The default recursive comparison behavior is configured as follows:

Returns:RecursiveComparisonAssert<?>

a new RecursiveComparisonAssert instance

Annotations
@Override
@Beta
See Also
RecursiveComparisonConfiguration
usingRecursiveComparisonback to summary
public RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration)

Overrides org.assertj.core.api.AbstractAssert.usingRecursiveComparison.

Same as usingRecursiveComparison() but allows to specify your own RecursiveComparisonConfiguration.

Parameters
recursiveComparisonConfiguration:RecursiveComparisonConfiguration

the RecursiveComparisonConfiguration used in the chained isEqualTo assertion.

Returns:RecursiveComparisonAssert<?>

a new RecursiveComparisonAssert instance built with the given RecursiveComparisonConfiguration.

Annotations
@Override
usingValueComparatorback to summary
public SELF usingValueComparator(Comparator<? super VALUE> customComparator)

Use given custom comparator instead of relying on actual type A equals method to compare the Optional value's object for incoming assertion checks.

Custom comparator is bound to assertion instance, meaning that if a new assertion is created, it will use default comparison strategy.

Examples :

 TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);
TolkienCharacter frodoClone = new TolkienCharacter("Frodo", 33, HOBBIT);

// Fail if equals has not been overridden in TolkienCharacter as equals default implementation only compares references
assertThat(Optional.of(frodo)).contains(frodoClone);

// frodo and frodoClone are equals when doing a field by field comparison.
assertThat(Optional.of(frodo)).usingValueComparator(new FieldByFieldComparator()).contains(frodoClone);
Parameters
customComparator:Comparator<? super VALUE>

the comparator to use for incoming assertion checks.

Returns:SELF

this assertion object.

Annotations
@CheckReturnValue
Exceptions
NullPointerException:
if the given comparator is null.