Class MockSettingsImpl<T>
- java.lang.Object
-
- org.mockito.internal.creation.settings.CreationSettings<T>
-
- org.mockito.internal.creation.MockSettingsImpl<T>
-
- All Implemented Interfaces:
java.io.Serializable
,MockCreationSettings<T>
,MockSettings
public class MockSettingsImpl<T> extends CreationSettings<T> implements MockSettings, MockCreationSettings<T>
- See Also:
- Serialized Form
-
-
Field Summary
Fields Modifier and Type Field Description private java.lang.Object[]
constructorArgs
private java.lang.Object
outerClassInstance
private static long
serialVersionUID
private boolean
useConstructor
-
Fields inherited from class org.mockito.internal.creation.settings.CreationSettings
defaultAnswer, extraInterfaces, invocationListeners, lenient, mockName, name, serializableMode, spiedInstance, stripAnnotations, stubbingLookupListeners, stubOnly, typeToMock, verificationStartedListeners
-
-
Constructor Summary
Constructors Constructor Description MockSettingsImpl()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description (package private) static <T> void
addListeners(T[] listeners, java.util.List<T> container, java.lang.String method)
<T2> MockCreationSettings<T2>
build(java.lang.Class<T2> typeToMock)
Creates immutable view of mock settings used later by Mockito.<T2> MockCreationSettings<T2>
buildStatic(java.lang.Class<T2> classToMock)
Creates immutable view of mock settings used later by Mockito, for use within a static mocking.MockSettings
defaultAnswer(Answer defaultAnswer)
Specifies default answers to interactions.MockSettings
extraInterfaces(java.lang.Class<?>... extraInterfaces)
Specifies extra interfaces the mock should implement.java.lang.Object[]
getConstructorArgs()
Used when arguments should be passed to the mocked object's constructor, regardless of whether these arguments are supplied directly, or whether they include the outer instance.Answer<java.lang.Object>
getDefaultAnswer()
the default answer for this mock, seeMockSettings.defaultAnswer(org.mockito.stubbing.Answer)
.java.util.Set<java.lang.Class<?>>
getExtraInterfaces()
the extra interfaces the mock object should implement.MockName
getMockName()
the name of this mock, as printed on verification errors; seeMockSettings.name(java.lang.String)
.java.lang.Object
getOuterClassInstance()
Used when mocking non-static inner classes in conjunction withMockCreationSettings.isUsingConstructor()
java.lang.Object
getSpiedInstance()
the spied instance - needed for spies.java.lang.Class<T>
getTypeToMock()
Mocked type.boolean
hasInvocationListeners()
MockSettings
invocationListeners(InvocationListener... listeners)
Registers a listener for method invocations on this mock.private boolean
invocationListenersContainsType(java.lang.Class<?> clazz)
boolean
isStubOnly()
Whether the mock is only for stubbing, i.e.boolean
isUsingConstructor()
Informs whether the mock instance should be created via constructorMockSettings
lenient()
Lenient mocks bypass "strict stubbing" validation (seeStrictness.STRICT_STUBS
).MockSettings
name(java.lang.String name)
Specifies mock name.MockSettings
outerInstance(java.lang.Object outerClassInstance)
Makes it possible to mock non-static inner classes in conjunction withMockSettings.useConstructor(Object...)
.private static java.util.Set<java.lang.Class<?>>
prepareExtraInterfaces(CreationSettings settings)
MockSettings
serializable()
Configures the mock to be serializable.MockSettings
serializable(SerializableMode mode)
Configures the mock to be serializable with a specific serializable mode.MockSettings
spiedInstance(java.lang.Object spiedInstance)
Specifies the instance to spy on.MockSettings
stubbingLookupListeners(StubbingLookupListener... listeners)
Add stubbing lookup listener to the mock object.MockSettingsImpl<T>
stubOnly()
A stub-only mock does not record method invocations, thus saving memory but disallowing verification of invocations.MockSettings
useConstructor(java.lang.Object... constructorArgs)
Mockito attempts to use constructor when creating instance of the mock.private static <T> CreationSettings<T>
validatedSettings(java.lang.Class<T> typeToMock, CreationSettings<T> source)
private static <T> CreationSettings<T>
validatedStaticSettings(java.lang.Class<T> classToMock, CreationSettings<T> source)
MockSettings
verboseLogging()
Enables real-time logging of method invocations on this mock.MockSettings
verificationStartedListeners(VerificationStartedListener... listeners)
Registers a listener(s) that will be notified when user starts verification.MockSettings
withoutAnnotations()
By default, Mockito makes an attempt to preserve all annotation meta data on the mocked type and its methods to mirror the mocked type as closely as possible.-
Methods inherited from class org.mockito.internal.creation.settings.CreationSettings
getInvocationListeners, getName, getSerializableMode, getStubbingLookupListeners, getVerificationStartedListeners, isLenient, isSerializable, isStripAnnotations, setExtraInterfaces, setMockName, setSerializableMode, setTypeToMock
-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface org.mockito.mock.MockCreationSettings
getInvocationListeners, getSerializableMode, getStubbingLookupListeners, getVerificationStartedListeners, isLenient, isSerializable, isStripAnnotations
-
-
-
-
Field Detail
-
serialVersionUID
private static final long serialVersionUID
- See Also:
- Constant Field Values
-
useConstructor
private boolean useConstructor
-
outerClassInstance
private java.lang.Object outerClassInstance
-
constructorArgs
private java.lang.Object[] constructorArgs
-
-
Method Detail
-
serializable
public MockSettings serializable()
Description copied from interface:MockSettings
Configures the mock to be serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.WARNING: This should be rarely used in unit testing.
The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This was in a web environment and the objects from the external dependency were being serialized to pass between layers.
Example:
List serializableMock = mock(List.class, withSettings().serializable());
- Specified by:
serializable
in interfaceMockSettings
- Returns:
- settings instance so that you can fluently specify other settings
-
serializable
public MockSettings serializable(SerializableMode mode)
Description copied from interface:MockSettings
Configures the mock to be serializable with a specific serializable mode. With this feature you can use a mock in a place that requires dependencies to be serializable.WARNING: This should be rarely used in unit testing.
The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This was in a web environment and the objects from the external dependency were being serialized to pass between layers.
List serializableMock = mock(List.class, withSettings().serializable(SerializableMode.ACROSS_CLASSLOADERS));
- Specified by:
serializable
in interfaceMockSettings
- Parameters:
mode
- serialization mode- Returns:
- settings instance so that you can fluently specify other settings
-
extraInterfaces
public MockSettings extraInterfaces(java.lang.Class<?>... extraInterfaces)
Description copied from interface:MockSettings
Specifies extra interfaces the mock should implement. Might be useful for legacy code or some corner cases.This mysterious feature should be used very occasionally. The object under test should know exactly its collaborators & dependencies. If you happen to use it often than please make sure you are really producing simple, clean & readable code.
Examples:
Foo foo = mock(Foo.class, withSettings().extraInterfaces(Bar.class, Baz.class)); //now, the mock implements extra interfaces, so following casting is possible: Bar bar = (Bar) foo; Baz baz = (Baz) foo;
- Specified by:
extraInterfaces
in interfaceMockSettings
- Parameters:
extraInterfaces
- extra interfaces the should implement.- Returns:
- settings instance so that you can fluently specify other settings
-
getMockName
public MockName getMockName()
Description copied from interface:MockCreationSettings
the name of this mock, as printed on verification errors; seeMockSettings.name(java.lang.String)
.- Specified by:
getMockName
in interfaceMockCreationSettings<T>
- Overrides:
getMockName
in classCreationSettings<T>
-
getExtraInterfaces
public java.util.Set<java.lang.Class<?>> getExtraInterfaces()
Description copied from interface:MockCreationSettings
the extra interfaces the mock object should implement.- Specified by:
getExtraInterfaces
in interfaceMockCreationSettings<T>
- Overrides:
getExtraInterfaces
in classCreationSettings<T>
-
getSpiedInstance
public java.lang.Object getSpiedInstance()
Description copied from interface:MockCreationSettings
the spied instance - needed for spies.- Specified by:
getSpiedInstance
in interfaceMockCreationSettings<T>
- Overrides:
getSpiedInstance
in classCreationSettings<T>
-
name
public MockSettings name(java.lang.String name)
Description copied from interface:MockSettings
Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators. If you have too many mocks then refactor the code so that it's easy to test/debug without necessity of naming mocks.
If you use @Mock annotation then you've got naming mocks for free! @Mock uses field name as mock name.
Read more.
Examples:
Foo foo = mock(Foo.class, withSettings().name("foo")); //Below does exactly the same: Foo foo = mock(Foo.class, "foo");
- Specified by:
name
in interfaceMockSettings
- Parameters:
name
- the name of the mock, later used in all verification errors- Returns:
- settings instance so that you can fluently specify other settings
-
spiedInstance
public MockSettings spiedInstance(java.lang.Object spiedInstance)
Description copied from interface:MockSettings
Specifies the instance to spy on. Makes sense only for spies/partial mocks. Sets the instance that will be spied. Actually copies the internal fields of the passed instance to the mock.As usual you are going to read the partial mock warning: Object oriented programming is more or less about tackling complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.
However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.
Enough warnings about partial mocks, see an example how spiedInstance() works:
About stubbing for a partial mock, as it is a spy it will always call the real method, unless you use theFoo foo = mock(Foo.class, withSettings().spiedInstance(fooInstance)); //Below does exactly the same: Foo foo = spy(fooInstance);
doReturn
|Throw
|Answer
|CallRealMethod
stubbing style. Example:List list = new LinkedList(); List spy = spy(list); //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn("foo"); //You have to use doReturn() for stubbing doReturn("foo").when(spy).get(0);
- Specified by:
spiedInstance
in interfaceMockSettings
- Parameters:
spiedInstance
- to spy on- Returns:
- settings instance so that you can fluently specify other settings
-
defaultAnswer
public MockSettings defaultAnswer(Answer defaultAnswer)
Description copied from interface:MockSettings
Specifies default answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems.It is the default answer so it will be used only when you don't stub the method call.
Foo mock = mock(Foo.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS)); Foo mockTwo = mock(Foo.class, withSettings().defaultAnswer(new YourOwnAnswer())); //Below does exactly the same: Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
- Specified by:
defaultAnswer
in interfaceMockSettings
- Parameters:
defaultAnswer
- default answer to be used by mock when not stubbed- Returns:
- settings instance so that you can fluently specify other settings
-
getDefaultAnswer
public Answer<java.lang.Object> getDefaultAnswer()
Description copied from interface:MockCreationSettings
the default answer for this mock, seeMockSettings.defaultAnswer(org.mockito.stubbing.Answer)
.- Specified by:
getDefaultAnswer
in interfaceMockCreationSettings<T>
- Overrides:
getDefaultAnswer
in classCreationSettings<T>
-
stubOnly
public MockSettingsImpl<T> stubOnly()
Description copied from interface:MockSettings
A stub-only mock does not record method invocations, thus saving memory but disallowing verification of invocations.Example:
List stubOnly = mock(List.class, withSettings().stubOnly());
- Specified by:
stubOnly
in interfaceMockSettings
- Returns:
- settings instance so that you can fluently specify other settings
-
useConstructor
public MockSettings useConstructor(java.lang.Object... constructorArgs)
Description copied from interface:MockSettings
Mockito attempts to use constructor when creating instance of the mock. This is particularly useful for spying on abstract classes. See alsoMockito.spy(Class)
.Example:
//Robust API, via settings builder: OtherAbstract spy = mock(OtherAbstract.class, withSettings() .useConstructor().defaultAnswer(CALLS_REAL_METHODS)); //Mocking an abstract class with constructor arguments SomeAbstract spy = mock(SomeAbstract.class, withSettings() .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS)); //Mocking a non-static inner abstract class: InnerAbstract spy = mock(InnerAbstract.class, withSettings() .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
- Specified by:
useConstructor
in interfaceMockSettings
- Parameters:
constructorArgs
- The arguments to pass to the constructor. Not passing any arguments means that a parameter-less constructor will be called- Returns:
- settings instance so that you can fluently specify other settings
-
outerInstance
public MockSettings outerInstance(java.lang.Object outerClassInstance)
Description copied from interface:MockSettings
Makes it possible to mock non-static inner classes in conjunction withMockSettings.useConstructor(Object...)
.Example:
InnerClass mock = mock(InnerClass.class, withSettings() .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
- Specified by:
outerInstance
in interfaceMockSettings
- Returns:
- settings instance so that you can fluently specify other settings
-
withoutAnnotations
public MockSettings withoutAnnotations()
Description copied from interface:MockSettings
By default, Mockito makes an attempt to preserve all annotation meta data on the mocked type and its methods to mirror the mocked type as closely as possible. If this is not desired, this option can be used to disable this behavior.- Specified by:
withoutAnnotations
in interfaceMockSettings
- Returns:
- settings instance so that you can fluently specify other settings
-
isUsingConstructor
public boolean isUsingConstructor()
Description copied from interface:MockCreationSettings
Informs whether the mock instance should be created via constructor- Specified by:
isUsingConstructor
in interfaceMockCreationSettings<T>
- Overrides:
isUsingConstructor
in classCreationSettings<T>
-
getOuterClassInstance
public java.lang.Object getOuterClassInstance()
Description copied from interface:MockCreationSettings
Used when mocking non-static inner classes in conjunction withMockCreationSettings.isUsingConstructor()
- Specified by:
getOuterClassInstance
in interfaceMockCreationSettings<T>
- Overrides:
getOuterClassInstance
in classCreationSettings<T>
- Returns:
- the outer class instance used for creation of the mock object via the constructor.
-
getConstructorArgs
public java.lang.Object[] getConstructorArgs()
Description copied from interface:MockCreationSettings
Used when arguments should be passed to the mocked object's constructor, regardless of whether these arguments are supplied directly, or whether they include the outer instance.- Specified by:
getConstructorArgs
in interfaceMockCreationSettings<T>
- Overrides:
getConstructorArgs
in classCreationSettings<T>
- Returns:
- An array of arguments that are passed to the mocked object's constructor. If
MockCreationSettings.getOuterClassInstance()
is available, it is prepended to the passed arguments.
-
isStubOnly
public boolean isStubOnly()
Description copied from interface:MockCreationSettings
Whether the mock is only for stubbing, i.e. does not remember parameters on its invocation and therefore cannot be used for verification- Specified by:
isStubOnly
in interfaceMockCreationSettings<T>
- Overrides:
isStubOnly
in classCreationSettings<T>
-
verboseLogging
public MockSettings verboseLogging()
Description copied from interface:MockSettings
Enables real-time logging of method invocations on this mock. Can be used during test debugging in order to find wrong interactions with this mock.Invocations are logged as they happen to the standard output stream.
Calling this method multiple times makes no difference.
Example:
List mockWithLogger = mock(List.class, withSettings().verboseLogging());
- Specified by:
verboseLogging
in interfaceMockSettings
- Returns:
- settings instance so that you can fluently specify other settings
-
invocationListeners
public MockSettings invocationListeners(InvocationListener... listeners)
Description copied from interface:MockSettings
Registers a listener for method invocations on this mock. The listener is notified every time a method on this mock is called.Multiple listeners may be added and they will be notified in the order they were supplied. Example:
See theList mockWithListener = mock(List.class, withSettings().invocationListeners(new YourInvocationListener()));
listener interface
for more details.- Specified by:
invocationListeners
in interfaceMockSettings
- Parameters:
listeners
- The invocation listeners to add. May not be null.- Returns:
- settings instance so that you can fluently specify other settings
-
stubbingLookupListeners
public MockSettings stubbingLookupListeners(StubbingLookupListener... listeners)
Description copied from interface:MockSettings
Add stubbing lookup listener to the mock object. Multiple listeners may be added and they will be notified orderly. For use cases and more info seeStubbingLookupListener
. Example:List mockWithListener = mock(List.class, withSettings().stubbingLookupListeners(new YourStubbingLookupListener()));
- Specified by:
stubbingLookupListeners
in interfaceMockSettings
- Parameters:
listeners
- The stubbing lookup listeners to add. May not be null.- Returns:
- settings instance so that you can fluently specify other settings
-
addListeners
static <T> void addListeners(T[] listeners, java.util.List<T> container, java.lang.String method)
-
verificationStartedListeners
public MockSettings verificationStartedListeners(VerificationStartedListener... listeners)
Description copied from interface:MockSettings
Registers a listener(s) that will be notified when user starts verification. SeeVerificationStartedListener
on how such listener can be useful.When multiple listeners are added, they are notified in order they were supplied. There is no reason to supply multiple listeners but we wanted to keep the API simple and consistent with
MockSettings.invocationListeners(InvocationListener...)
.Throws exception when any of the passed listeners is null or when the entire vararg array is null.
- Specified by:
verificationStartedListeners
in interfaceMockSettings
- Parameters:
listeners
- to be notified when user starts verification.- Returns:
- settings instance so that you can fluently specify other settings
-
invocationListenersContainsType
private boolean invocationListenersContainsType(java.lang.Class<?> clazz)
-
hasInvocationListeners
public boolean hasInvocationListeners()
-
getTypeToMock
public java.lang.Class<T> getTypeToMock()
Description copied from interface:MockCreationSettings
Mocked type. An interface or class the mock should implement / extend.- Specified by:
getTypeToMock
in interfaceMockCreationSettings<T>
- Overrides:
getTypeToMock
in classCreationSettings<T>
-
build
public <T2> MockCreationSettings<T2> build(java.lang.Class<T2> typeToMock)
Description copied from interface:MockSettings
Creates immutable view of mock settings used later by Mockito. Framework integrators can use this method to create instances of creation settings and use them in advanced use cases, for example to create invocations withInvocationFactory
, or to implement customMockHandler
. SinceMockCreationSettings
isNotExtensible
, Mockito public API needs a creation method for this type.- Specified by:
build
in interfaceMockSettings
- Type Parameters:
T2
- type to mock- Parameters:
typeToMock
- class to mock- Returns:
- immutable view of mock settings
-
buildStatic
public <T2> MockCreationSettings<T2> buildStatic(java.lang.Class<T2> classToMock)
Description copied from interface:MockSettings
Creates immutable view of mock settings used later by Mockito, for use within a static mocking. Framework integrators can use this method to create instances of creation settings and use them in advanced use cases, for example to create invocations withInvocationFactory
, or to implement customMockHandler
. SinceMockCreationSettings
isNotExtensible
, Mockito public API needs a creation method for this type.- Specified by:
buildStatic
in interfaceMockSettings
- Type Parameters:
T2
- type to mock- Parameters:
classToMock
- class to mock- Returns:
- immutable view of mock settings
-
lenient
public MockSettings lenient()
Description copied from interface:MockSettings
Lenient mocks bypass "strict stubbing" validation (seeStrictness.STRICT_STUBS
). When mock is declared as lenient none of its stubbings will be checked for potential stubbing problems such as 'unnecessary stubbing' (UnnecessaryStubbingException
) or for 'stubbing argument mismatch'PotentialStubbingProblem
.
For more information and an elaborate example, seeFoo mock = mock(Foo.class, withSettings.lenient());
Mockito.lenient()
.- Specified by:
lenient
in interfaceMockSettings
-
validatedSettings
private static <T> CreationSettings<T> validatedSettings(java.lang.Class<T> typeToMock, CreationSettings<T> source)
-
validatedStaticSettings
private static <T> CreationSettings<T> validatedStaticSettings(java.lang.Class<T> classToMock, CreationSettings<T> source)
-
prepareExtraInterfaces
private static java.util.Set<java.lang.Class<?>> prepareExtraInterfaces(CreationSettings settings)
-
-