Unit Test: Should I use null or Optional.empty() in thenReturn()?

Viewed 876

I test a Spring Data JPA method as shown below:

Optional<Country> findByUuid(final UUID uuid);

When I write Unit Test for this method, I can test it by using a return value of null or Optional.empty() in thenReturn() method.

when(demoRepository.findByUuid(uuid)).thenReturn(null);

// or

when(demoRepository.findByUuid(uuid)).thenReturn(Optional.empty());

So, which one is more proper way for this?

1 Answers

The latter.

When a method returns Optional, for all intents and purposes there's an implicit assumption that it's not nullable. If callers had to check not only for nullity but also for presence/absence of a value in the Optional, all code which called a method returning Optional would be horrendously verbose.

No client code should be checking whether an Optional return is null. Therefore using the former is overwhelmingly likely to produce null pointer exceptions.

Related