I have a Java method that returns an Optional. I\'d like to write an easy-to-read unit test for it that asserts that
the returned Optional has a value (i.e.
The below approach uses the fact that you can specify a default return for an optional. So your test method could be something like this:
@test
public void testThatOptionalHasValue() {
String expectedValue = "actual value";
String actualValue = Optional.ofNullable(testedMethod()).orElse("not " + expectedValue);
assertEquals("The values are not the same", expectedValue, actualValue);
}
This guarentees that if your method returns null, then the result can not be the same as the expected value.