When we're testing methods that return Optional objects, we may need to write assertions that either check if the Optional has a value or check the value inside it.
2. Test Whether an Optional Is Empty or Not
If we only need to find out whether the Optional has a value, we can assert on isPresent or isEmpty.
2.1. Test Optional Has a Value
If an Optional has a value, we can assert on Optional.isPresent:
However, the AssertJ library provides a more fluent way of expressing this:
2.2. Test Optional Is Empty
We can reverse the logic when using JUnit:
Also, in Java 11 onwards, we can use Optional.isEmpty:
However, AssertJ provides us a neat alternative too:
3. Testing the Value of an Optional
Often we want to test the value inside an Optional rather than just presence or absence.
3.1. Using JUnit Assertions
We can use Optional.get to provide the value and then write an assertion on that:
Optional<String> optional = Optional.of("SOMEVALUE"); assertEquals("SOMEVALUE", optional.get());
However, using get may cause an exception, which makes it harder to understand a test failure. So, we may prefer to assert whether the value is present first:
assertTrue(optional.isPresent()); assertEquals("SOMEVALUE", optional.get());
However, Optional supports the equals method, so we can use an Optional with the correct value in it as part of a general equality assertion:
Optional<String> expected = Optional.of("SOMEVALUE"); Optional<String> actual = Optional.of("SOMEVALUE"); assertEquals(expected, actual);
3.2. Using AssertJ
With AssertJ, we can use the hasValue fluent assertion:
In this article, we looked at a few ways to test Optional.
We saw how the built-in JUnit assertions can be used with isPresent and get. We also saw how Optional.equals provides us a way to compare Optional objects in our assertions.
Finally, we looked at the AssertJ assertions, which give us fluent language to check our Optional values.
As always, the code presented in this article is available over on GitHub.