244. Asserting equality of Optionals

Having two Optional objects in assertEquals() doesn't require unwrapped values. This is applicable because Optional.equals() compares the wrapped values, not the Optional objects. This is the source code of Optional.equals():

@Override
public boolean equals(Object obj) {

if (this == obj) {
return true;
}

if (!(obj instanceof Optional)) {
return false;
}

Optional<?> other = (Optional<?>) obj;

return Objects.equals(value, other.value);
}

Let's assume that we have two Optional objects:

Optional<String> actual = ...;
Optional<String> expected = ...;

// or
Optional actual = ...;
Optional expected = ...;

It is advisable to avoid a test written as follows:

// Avoid
@Test
public void givenOptionalsWhenTestEqualityThenTrue()
throws Exception {

assertEquals(expected.get(), actual.get());
}

If expected and/or actual is empty, then the get() method will cause an exception of the NoSuchElementException type.

It is better to use the following test:

// Prefer
@Test
public void givenOptionalsWhenTestEqualityThenTrue()
throws Exception {

assertEquals(expected, actual);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.80.101