Class AbstractOptionalAssert<SELF extends AbstractOptionalAssert<SELF,VALUE>,VALUE>
- Type Parameters:
SELF
- the "self" type of this assertion class.VALUE
- type of the value contained in theOptional
.
- All Implemented Interfaces:
Assert<SELF,
,Optional<VALUE>> Descriptable<SELF>
,ExtensionPoints<SELF,
Optional<VALUE>>
- Direct Known Subclasses:
OptionalAssert
Optional
.- Author:
- Jean-Christophe Gay, Nicolai Parlog, Grzegorz Piwowarek
-
Field Summary
Fields inherited from class org.assertj.core.api.AbstractAssert
actual, info, myself, objects, throwUnsupportedExceptionOnEquals
-
Constructor Summary
ModifierConstructorDescriptionprotected
AbstractOptionalAssert
(Optional<VALUE> actual, Class<?> selfType) -
Method Summary
Modifier and TypeMethodDescriptionVerifies that the actualOptional
contains the given value (alias ofhasValue(Object)
).containsInstanceOf
(Class<?> clazz) Verifies that the actualOptional
contains a value that is an instance of the argument.containsSame
(VALUE expectedValue) Verifies that the actualOptional
contains the instance given as an argument (i.e.<U> AbstractOptionalAssert
<?, U> CallflatMap
on theOptional
under test, assertions chained afterwards are performed on theOptional
resulting from the flatMap call.get()
Verifies that the actualOptional
is notnull
and not empty and returns an Object assertion that allows chaining (object) assertions on the optional value.<ASSERT extends AbstractAssert<?,
?>>
ASSERTget
(InstanceOfAssertFactory<?, ASSERT> assertFactory) Verifies that the actualOptional
is notnull
and not empty and returns an new assertion instance to chain assertions on the optional value.Verifies that the actualOptional
contains the given value (alias ofcontains(Object)
).hasValueSatisfying
(Consumer<VALUE> requirement) hasValueSatisfying
(Condition<? super VALUE> condition) isEmpty()
Verifies that the actualOptional
is empty.Verifies that there is a value present in the actualOptional
, it's an alias ofisPresent()
.Verifies that there is a value present in the actualOptional
.<U> AbstractOptionalAssert
<?, U> Callmap
on theOptional
under test, assertions chained afterwards are performed on theOptional
resulting from the map call.Revert to standard comparison for incoming assertionOptional
value checks.Deprecated.This method is deprecated because it performs a shallow field by field comparison, i.e.Asserts that the given predicate is met for all fields of the object under test recursively (but not the object itself).usingRecursiveAssertion
(org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration recursiveAssertionConfiguration) The same asusingRecursiveAssertion()
, but this method allows the developer to pass in an explicit recursion configuration.Enable using a recursive field by field comparison strategy when calling the chainedRecursiveComparisonAssert
,usingRecursiveComparison
(RecursiveComparisonConfiguration recursiveComparisonConfiguration) Same asusingRecursiveComparison()
but allows to specify your ownRecursiveComparisonConfiguration
.usingValueComparator
(Comparator<? super VALUE> customComparator) Use given custom comparator instead of relying on actual type Aequals
method to compare theOptional
value's object for incoming assertion checks.Methods inherited from class org.assertj.core.api.AbstractAssert
areEqual, asInstanceOf, asList, assertionError, asString, describedAs, descriptionText, doesNotHave, doesNotHaveSameClassAs, doesNotHaveSameHashCodeAs, doesNotHaveToString, doesNotHaveToString, equals, extracting, extracting, failure, failureWithActualExpected, failWithActualExpectedAndMessage, failWithMessage, getWritableAssertionInfo, has, hashCode, hasSameClassAs, hasSameHashCodeAs, hasToString, 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, satisfiesForProxy, 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, as, as, describedAs, describedAs
-
Constructor Details
-
AbstractOptionalAssert
-
-
Method Details
-
isPresent
Verifies that there is a value present in the actualOptional
.Assertion will pass :
Assertion will fail :assertThat(Optional.of("something")).isPresent();
assertThat(Optional.empty()).isPresent();
- Returns:
- this assertion object.
-
isNotEmpty
Verifies that there is a value present in the actualOptional
, it's an alias ofisPresent()
.Assertion will pass :
Assertion will fail :assertThat(Optional.of("something")).isNotEmpty();
assertThat(Optional.empty()).isNotEmpty();
- Returns:
- this assertion object.
-
isEmpty
Verifies that the actualOptional
is empty.Assertion will pass :
Assertion will fail :assertThat(Optional.empty()).isEmpty();
assertThat(Optional.of("something")).isEmpty();
- Returns:
- this assertion object.
-
isNotPresent
Verifies that the actualOptional
is empty (alias ofisEmpty()
).Assertion will pass :
Assertion will fail :assertThat(Optional.empty()).isNotPresent();
assertThat(Optional.of("something")).isNotPresent();
- Returns:
- this assertion object.
-
contains
Verifies that the actualOptional
contains the given value (alias ofhasValue(Object)
).Assertion will pass :
Assertion will fail :assertThat(Optional.of("something")).contains("something"); assertThat(Optional.of(10)).contains(10);
assertThat(Optional.of("something")).contains("something else"); assertThat(Optional.of(20)).contains(10);
- Parameters:
expectedValue
- the expected value inside theOptional
.- Returns:
- this assertion object.
-
hasValueSatisfying
Verifies that the actualOptional
contains a value and gives this value to the givenConsumer
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 :
Assertions will fail :// 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"); });
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
- to further assert on the object contained inside theOptional
.- Returns:
- this assertion object.
-
hasValueSatisfying
Verifies that the actualOptional
contains a value which satisfies the givenCondition
.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
- the given condition.- Returns:
- this assertion object.
- Throws:
AssertionError
- if the actualOptional
is null or empty.NullPointerException
- if the given condition isnull
.AssertionError
- if the actual value does not satisfy the given condition.- Since:
- 3.6.0
-
hasValue
Verifies that the actualOptional
contains the given value (alias ofcontains(Object)
).Assertion will pass :
Assertion will fail :assertThat(Optional.of("something")).hasValue("something"); assertThat(Optional.of(10)).contains(10);
assertThat(Optional.of("something")).hasValue("something else"); assertThat(Optional.of(20)).contains(10);
- Parameters:
expectedValue
- the expected value inside theOptional
.- Returns:
- this assertion object.
-
containsInstanceOf
Verifies that the actualOptional
contains a value that is an instance of the argument.Assertions will pass:
Assertion will fail:assertThat(Optional.of("something")).containsInstanceOf(String.class) .containsInstanceOf(Object.class); assertThat(Optional.of(10)).containsInstanceOf(Integer.class);
assertThat(Optional.of("something")).containsInstanceOf(Integer.class);
- Parameters:
clazz
- the expected class of the value inside theOptional
.- 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, useget()
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-comparisonUse field/property by field/property comparison (including inherited fields/properties) instead of relying on actual type Aequals
method to compare theOptional
value's object for incoming assertion checks. Private fields are included but this can be disabled usingAssertions.setAllowExtractingPrivateFields(boolean)
.This can be handy if
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 itsequals
method of theOptional
value's object to compare does not suit you.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:
this
assertion object.
-
usingValueComparator
Use given custom comparator instead of relying on actual type Aequals
method to compare theOptional
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
- the comparator to use for incoming assertion checks.- Returns:
this
assertion object.- Throws:
NullPointerException
- if the given comparator isnull
.
-
usingDefaultValueComparator
Revert to standard comparison for incoming assertionOptional
value checks.This method should be used to disable a custom comparison strategy set by calling
usingValueComparator(Comparator)
.- Returns:
this
assertion object.
-
containsSame
Verifies that the actualOptional
contains the instance given as an argument (i.e. it must be the same instance).Assertion will pass :
Assertion will fail :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);
// 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
- the expected value inside theOptional
.- Returns:
- this assertion object.
-
flatMap
CallflatMap
on theOptional
under test, assertions chained afterwards are performed on theOptional
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");
- Type Parameters:
U
- the type wrapped in theOptional
after theflatMap
operation.- Parameters:
mapper
- theFunction
to use in theflatMap
operation.- Returns:
- a new
AbstractOptionalAssert
for assertions chaining on the flatMap of the Optional. - Throws:
AssertionError
- if the actualOptional
is null.- Since:
- 3.6.0
-
map
Callmap
on theOptional
under test, assertions chained afterwards are performed on theOptional
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);
- Type Parameters:
U
- the type wrapped in theOptional
after themap
operation.- Parameters:
mapper
- theFunction
to use in themap
operation.- Returns:
- a new
AbstractOptionalAssert
for assertions chaining on the map of the Optional. - Throws:
AssertionError
- if the actualOptional
is null.- Since:
- 3.6.0
-
get
Verifies that the actualOptional
is notnull
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:
- a new
AbstractObjectAssert
for assertions chaining on the value of the Optional. - Throws:
AssertionError
- if the actualOptional
is null.AssertionError
- if the actualOptional
is empty.- Since:
- 3.9.0
- See Also:
-
get
public <ASSERT extends AbstractAssert<?,?>> ASSERT get(InstanceOfAssertFactory<?, ASSERT> assertFactory) Verifies that the actualOptional
is notnull
and not empty and returns an new assertion instance to chain assertions on the optional value.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:
// 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();
- Type Parameters:
ASSERT
- the type of the resultingAssert
- Parameters:
assertFactory
- the factory which verifies the type and creates the newAssert
- Returns:
- a new narrowed
Assert
instance for assertions chaining on the value of the Optional - Throws:
NullPointerException
- if the given factory isnull
AssertionError
- if the actualOptional
is nullAssertionError
- if the actualOptional
is empty- Since:
- 3.14.0
-
usingRecursiveComparison
Enable using a recursive field by field comparison strategy when calling the chainedRecursiveComparisonAssert
,Example:
A detailed documentation for the recursive comparison is available here: https://assertj.github.io/doc/#assertj-core-recursive-comparison.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);
The default recursive comparison behavior is
configured
as follows:- different types of iterable can be compared by default as in the example, this can be turned off by calling
withStrictTypeChecking
. - overridden equals methods are used in the comparison (unless stated otherwise - see https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-equals)
- the following types are compared with these comparators:
java.lang.Double
:DoubleComparator
with precision of 1.0E-15java.lang.Float
:FloatComparator
with precision of 1.0E-6- any comparators previously registered with
AbstractIterableAssert.usingComparatorForType(Comparator, Class)
- Overrides:
usingRecursiveComparison
in classAbstractAssert<SELF extends AbstractOptionalAssert<SELF,
VALUE>, Optional<VALUE>> - Returns:
- a new
RecursiveComparisonAssert
instance - See Also:
- different types of iterable can be compared by default as in the example, this can be turned off by calling
-
usingRecursiveComparison
public RecursiveComparisonAssert<?> usingRecursiveComparison(RecursiveComparisonConfiguration recursiveComparisonConfiguration) Same asusingRecursiveComparison()
but allows to specify your ownRecursiveComparisonConfiguration
.- Overrides:
usingRecursiveComparison
in classAbstractAssert<SELF extends AbstractOptionalAssert<SELF,
VALUE>, Optional<VALUE>> - Parameters:
recursiveComparisonConfiguration
- theRecursiveComparisonConfiguration
used in the chainedisEqualTo
assertion.- Returns:
- a new
RecursiveComparisonAssert
instance built with the givenRecursiveComparisonConfiguration
.
-
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
Predicate
applied to them (including primitive fields), no fields are excluded, but:- The recursion does not enter into Java Class Library types (java.*, javax.*)
- The
Predicate
is applied toCollection
and array elements (but not the collection/array itself) - The
Predicate
is applied toMap
values but not the map itself or its keys - The
Predicate
is applied toOptional
and primitive optional values
You can change how the recursive assertion deals with arrays, collections, maps and optionals, see:
RecursiveAssertionAssert.withCollectionAssertionPolicy(RecursiveAssertionConfiguration.CollectionAssertionPolicy)
for collections and arraysRecursiveAssertionAssert.withMapAssertionPolicy(RecursiveAssertionConfiguration.MapAssertionPolicy)
for mapsRecursiveAssertionAssert.withOptionalAssertionPolicy(RecursiveAssertionConfiguration.OptionalAssertionPolicy)
for optionals
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.
- Overrides:
usingRecursiveAssertion
in classAbstractAssert<SELF extends AbstractOptionalAssert<SELF,
VALUE>, Optional<VALUE>> - Returns:
- A new instance of
RecursiveAssertionAssert
built with a defaultRecursiveAssertionConfiguration
.
-
usingRecursiveAssertion
public RecursiveAssertionAssert usingRecursiveAssertion(org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration recursiveAssertionConfiguration) 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
Collection
and array objects - Treatment of
Map
objects - Treatment of Optional and primitive Optional objects
Please refer to the documentation of
RecursiveAssertionConfiguration.Builder
for more details.- Overrides:
usingRecursiveAssertion
in classAbstractAssert<SELF extends AbstractOptionalAssert<SELF,
VALUE>, Optional<VALUE>> - Parameters:
recursiveAssertionConfiguration
- The recursion configuration described above.- Returns:
- A new instance of
RecursiveAssertionAssert
built with a defaultRecursiveAssertionConfiguration
.
-