LS Price Increase Launch

The Price of all “Learn Spring” course packages will increase by $40 on next Friday:

>> GET ACCESS NOW

1. Overview

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.

In this short tutorial, we'll look at how to write these assertions using functions from both JUnit and AssertJ.

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:

assertTrue(optional.isPresent());

However, the AssertJ library provides a more fluent way of expressing this:

assertThat(optional).isNotEmpty();

2.2. Test Optional is Empty

We can reverse the logic when using JUnit:

assertFalse(optional.isPresent());

Also, in Java 11 onwards, we can use Optional.isEmpty:

assertTrue(optional.isEmpty());

However, AssertJ provides us a neat alternative too:

assertThat(optional).isEmpty();

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:

assertThat(Optional.of("SOMEVALUE")).hasValue("SOMEVALUE");

4. Conclusion

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.

LS Price Increase Launch

The Price of all “Learn Spring” course packages will increase by $40 on next Friday:

>> GET ACCESS NOW
Junit footer banner
guest
0 Comments
Inline Feedbacks
View all comments