Search code examples
javaunit-testingjmockit

Is Optional cascaded?


What's the behavior when cascading mocks that return Optional? My expectation is that the returned Optional object is also a mock.

However, the test below shows that that's not the case:

@RunWith(JMockit.class)
public class CascadingTest {
    public static interface Foo {
        Optional<Bar> getOptionalBar();
    }

    public static interface Bar {
    }

    @Test
    public void cascadingOptional(@Mocked final Foo foo) {
        final Optional<Bar> opt = foo.getOptionalBar();
        assertThat(opt.get(), is(not(nullValue())));
    }
}

The cascadingOptional test due to the exception thrown by opt.get():

java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)
    at jmockit.CascadingTest.cascadingOptional(CascadingTest.java:39)

which seems to indicate opt is not a mock. Btw, how to (directly) check if an object is a JMockit mock?

Thanks

JMockit v1.17


Solution

  • The mocking API documentation specifies what is returned by default from mocked methods, according to their return types:

    If no result is recorded for a given expectation, then all matching invocations will return the appropriate default value according to the method return type:

    • Most java.lang types (String, Object, etc.): returns null.
    • java.math types (BigDecimal, etc.): returns null.
    • Primitive/wrapper types: returns the standard default value (false for boolean/Boolean, 0 for int/Integer, and so on).
    • java.util.List, java.util.Collection, or java.lang.Iterable: returns Collections.EMPTY_LIST.
    • java.util.Iterator or java.util.ListIterator: returns an empty iterator.
    • java.util.Set: returns Collections.EMPTY_SET.
    • java.util.SortedSet: returns an unmodifiable empty sorted set.
    • java.util.Map: returns Collections.EMPTY_MAP.
    • java.util.SortedMap: returns an unmodifiable empty sorted map.
    • java.util.Optional: returns Optional.empty().
    • Other reference types: returns a mocked instance through cascading.
    • Array types: returns an array with zero elements (empty) in each dimension.