Class ReturnsDeepStubs

  • All Implemented Interfaces:
    java.io.Serializable, Answer<java.lang.Object>
    Direct Known Subclasses:
    ReturnsDeepStubs.ReturnsDeepStubsSerializationFallback

    public class ReturnsDeepStubs
    extends java.lang.Object
    implements Answer<java.lang.Object>, java.io.Serializable
    Returning deep stub implementation.

    Will return previously created mock if the invocation matches.

    Supports nested generic information, with this answer you can write code like this :

    
         interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {}
    
         GenericsNest<?> mock = mock(GenericsNest.class, new ReturnsGenericDeepStubs());
         Number number = mock.entrySet().iterator().next().getValue().iterator().next();
     

    However this answer does not support generics information when the mock has been deserialized.

    See Also:
    Mockito.RETURNS_DEEP_STUBS, Answers.RETURNS_DEEP_STUBS, Serialized Form
    • Constructor Detail

      • ReturnsDeepStubs

        public ReturnsDeepStubs()
    • Method Detail

      • answer

        public java.lang.Object answer​(InvocationOnMock invocation)
                                throws java.lang.Throwable
        Specified by:
        answer in interface Answer<java.lang.Object>
        Parameters:
        invocation - the invocation on the mock.
        Returns:
        the value to be returned
        Throws:
        java.lang.Throwable - the throwable to be thrown
      • newDeepStubMock

        private java.lang.Object newDeepStubMock​(GenericMetadataSupport returnTypeGenericMetadata,
                                                 java.lang.Object parentMock)
        Creates a mock using the Generics Metadata.
      • Finally as we want to mock the actual type, but we want to pass along the contextual generics meta-data that was resolved for the current return type, for this to happen we associate to the mock an new instance of ReturnsDeepStubs answer in which we will store the returned type generic metadata.
Parameters:
returnTypeGenericMetadata - The metadata to use to create the new mock.
parentMock - The parent of the current deep stub mock.
Returns:
The mock