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 Optional is not empty) and that
the returned value is equal to an expected value.
Let's say my tested method is
Optional<String> testedMethod(){
return Optional.of("actual value");
}
TL;DR the best overall approach was suggested by Ole V. V.:
Other alternatives are discussed below.
There are several different ways to do this, depending on your taste for clarity of test results vs. conciseness of test writing. For this answer I'll stick to "stock" Java 8 and JUnit 4 with no additional dependencies.
One way, as suggested in a comment by Ole V.V., is simply to write
This mostly works but if the Optional is empty, then
get()
will throwNoSuchElementException
. This in turn causes JUnit to signal an error instead of a failure, which might not be what you want. It's also not very clear what's going on unless you already know thatget()
throws NSEE in this case.An alternative is
This also mostly works but it doesn't report the actual value if there's a mismatch, which might make debugging inconvenient.
Another alternative is
This gives the right failures and reports the actual value when there's a mismatch, but it's not very explicit about why
AssertionFailedError
is thrown. You might have to stare at it a while until you realize that AFE gets thrown when the Optional is empty.Still another alternative is
but this is starting to get verbose.
You could split this into two assertions,
but you had previously objected to this suggestion because of verbosity. This isn't really terribly verbose in my opinion, but it does have some cognitive overhead since there are two separate assertions, and it relies on the second only being checked if the first succeeds. This is not incorrect but it is a bit subtle.
Finally, if you're willing to create a bit of your own infrastructure, you could create a suitably-named subclass of
AssertionFailedError
and use it like this:Finally, in another comment, Ole V. V. suggested
This works quite well, and in fact this might be the best of all.
I use Hamcrest Optional for that:
You can add Hamcrest Optional to your dependencies by including it in your
build.gradle
: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:
This guarentees that if your method returns null, then the result can not be the same as the expected value.
You can also use AssertJ for fluent assertions
Why don’t you use
isPresent()
andget()
?