I started to use Guava Optional as a part of the null object pattern and would like to improve the use in Mockito, where null
is the default return value for mocked objects. To behave correctly one needs to explicitly tell Mockito to use Optional.absent()
instead:
import org.mockito.*;
import org.testng.*;
import org.testng.annotations.*;
import com.google.common.base.Optional;
public class Example {
@Mock
private MyObject underTest;
@Test
public void testExample() {
// fails
// assertNotNull(underTest.get());
Mockito.when(underTest.get()).thenReturn(Optional.absent());
Assert.assertNotNull(underTest.get());
}
public class MyObject {
public Optional<Object> get() {
return Optional.absent();
}
}
@BeforeClass
public void beforeClass() {
MockitoAnnotations.initMocks(this);
}
}
Is there a easy way to improve mockito to automatically return Optional.absent()
instead of null
if the actual type is Optional
?