public class MockSettingsImpl<T> extends CreationSettings<T> implements MockSettings, MockCreationSettings<T>
Modifier and Type | Field and Description |
---|---|
private java.lang.Object[] |
constructorArgs |
private java.lang.Object |
outerClassInstance |
private static long |
serialVersionUID |
private boolean |
useConstructor |
defaultAnswer, extraInterfaces, invocationListeners, lenient, mockName, name, serializableMode, spiedInstance, stripAnnotations, stubbingLookupListeners, stubOnly, typeToMock, verificationStartedListeners
Constructor and Description |
---|
MockSettingsImpl() |
Modifier and Type | Method and Description |
---|---|
private static <T> void |
addListeners(T[] listeners,
java.util.List<T> container,
java.lang.String method) |
<T> MockCreationSettings<T> |
build(java.lang.Class<T> typeToMock)
Creates immutable view of mock settings used later by Mockito.
|
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, see
MockSettings.defaultAnswer(org.mockito.stubbing.Answer) . |
java.util.Set<java.lang.Class<?>> |
getExtraInterfaces()
the extra interfaces the mock object should implement.
|
java.util.List<InvocationListener> |
getInvocationListeners()
InvocationListener instances attached to this mock, see MockSettings.invocationListeners(org.mockito.listeners.InvocationListener...) . |
MockName |
getMockName()
the name of this mock, as printed on verification errors; see
MockSettings.name(java.lang.String) . |
java.lang.Object |
getOuterClassInstance()
Used when mocking non-static inner classes in conjunction with
MockCreationSettings.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 constructor
|
MockSettings |
lenient()
Lenient mocks bypass "strict stubbing" validation (see
Strictness.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 with
MockSettings.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.
|
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) |
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.
|
getName, getSerializableMode, getStubbingLookupListeners, getVerificationStartedListeners, isLenient, isSerializable, isStripAnnotations, setExtraInterfaces, setMockName, setSerializableMode, setTypeToMock
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
getSerializableMode, getVerificationStartedListeners, isLenient, isSerializable, isStripAnnotations
private static final long serialVersionUID
private boolean useConstructor
private java.lang.Object outerClassInstance
private java.lang.Object[] constructorArgs
public MockSettings serializable()
MockSettings
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());
serializable
in interface MockSettings
public MockSettings serializable(SerializableMode mode)
MockSettings
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));
serializable
in interface MockSettings
mode
- serialization modepublic MockSettings extraInterfaces(java.lang.Class<?>... extraInterfaces)
MockSettings
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;
extraInterfaces
in interface MockSettings
extraInterfaces
- extra interfaces the should implement.public MockName getMockName()
MockCreationSettings
MockSettings.name(java.lang.String)
.getMockName
in interface MockCreationSettings<T>
getMockName
in class CreationSettings<T>
public java.util.Set<java.lang.Class<?>> getExtraInterfaces()
MockCreationSettings
getExtraInterfaces
in interface MockCreationSettings<T>
getExtraInterfaces
in class CreationSettings<T>
public java.lang.Object getSpiedInstance()
MockCreationSettings
getSpiedInstance
in interface MockCreationSettings<T>
getSpiedInstance
in class CreationSettings<T>
public MockSettings name(java.lang.String name)
MockSettings
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");
name
in interface MockSettings
name
- the name of the mock, later used in all verification errorspublic MockSettings spiedInstance(java.lang.Object spiedInstance)
MockSettings
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:
Foo foo = mock(Foo.class, withSettings().spiedInstance(fooInstance));
//Below does exactly the same:
Foo foo = spy(fooInstance);
About stubbing for a partial mock, as it is a spy it will always call the real method, unless you use the
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);
spiedInstance
in interface MockSettings
spiedInstance
- to spy onpublic MockSettings defaultAnswer(Answer defaultAnswer)
MockSettings
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());
defaultAnswer
in interface MockSettings
defaultAnswer
- default answer to be used by mock when not stubbedpublic Answer<java.lang.Object> getDefaultAnswer()
MockCreationSettings
MockSettings.defaultAnswer(org.mockito.stubbing.Answer)
.getDefaultAnswer
in interface MockCreationSettings<T>
getDefaultAnswer
in class CreationSettings<T>
public MockSettingsImpl<T> stubOnly()
MockSettings
Example:
List stubOnly = mock(List.class, withSettings().stubOnly());
stubOnly
in interface MockSettings
public MockSettings useConstructor(java.lang.Object... constructorArgs)
MockSettings
Mockito.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));
useConstructor
in interface MockSettings
constructorArgs
- The arguments to pass to the constructor. Not passing any arguments means that a parameter-less
constructor will be calledpublic MockSettings outerInstance(java.lang.Object outerClassInstance)
MockSettings
MockSettings.useConstructor(Object...)
.
Example:
InnerClass mock = mock(InnerClass.class, withSettings()
.useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
outerInstance
in interface MockSettings
public MockSettings withoutAnnotations()
MockSettings
withoutAnnotations
in interface MockSettings
public boolean isUsingConstructor()
MockCreationSettings
isUsingConstructor
in interface MockCreationSettings<T>
isUsingConstructor
in class CreationSettings<T>
public java.lang.Object getOuterClassInstance()
MockCreationSettings
MockCreationSettings.isUsingConstructor()
getOuterClassInstance
in interface MockCreationSettings<T>
getOuterClassInstance
in class CreationSettings<T>
public java.lang.Object[] getConstructorArgs()
MockCreationSettings
getConstructorArgs
in interface MockCreationSettings<T>
getConstructorArgs
in class CreationSettings<T>
MockCreationSettings.getOuterClassInstance()
is available, it is prepended to the passed arguments.public boolean isStubOnly()
MockCreationSettings
isStubOnly
in interface MockCreationSettings<T>
isStubOnly
in class CreationSettings<T>
public MockSettings verboseLogging()
MockSettings
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());
verboseLogging
in interface MockSettings
public MockSettings invocationListeners(InvocationListener... listeners)
MockSettings
Multiple listeners may be added and they will be notified in the order they were supplied. Example:
List mockWithListener = mock(List.class, withSettings().invocationListeners(new YourInvocationListener()));
See the listener interface
for more details.invocationListeners
in interface MockSettings
listeners
- The invocation listeners to add. May not be null.private static <T> void addListeners(T[] listeners, java.util.List<T> container, java.lang.String method)
public MockSettings verificationStartedListeners(VerificationStartedListener... listeners)
MockSettings
VerificationStartedListener
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.
verificationStartedListeners
in interface MockSettings
listeners
- to be notified when user starts verification.private boolean invocationListenersContainsType(java.lang.Class<?> clazz)
public java.util.List<InvocationListener> getInvocationListeners()
MockCreationSettings
InvocationListener
instances attached to this mock, see MockSettings.invocationListeners(org.mockito.listeners.InvocationListener...)
.getInvocationListeners
in interface MockCreationSettings<T>
getInvocationListeners
in class CreationSettings<T>
public boolean hasInvocationListeners()
public java.lang.Class<T> getTypeToMock()
MockCreationSettings
getTypeToMock
in interface MockCreationSettings<T>
getTypeToMock
in class CreationSettings<T>
public <T> MockCreationSettings<T> build(java.lang.Class<T> typeToMock)
MockSettings
InvocationFactory
,
or to implement custom MockHandler
.
Since MockCreationSettings
is NotExtensible
, Mockito public API needs a creation method for this type.build
in interface MockSettings
T
- type to mocktypeToMock
- class to mockpublic MockSettings lenient()
MockSettings
Strictness.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
.
Foo mock = mock(Foo.class, withSettings.lenient());
For more information and an elaborate example, see Mockito.lenient()
.lenient
in interface MockSettings
private static <T> CreationSettings<T> validatedSettings(java.lang.Class<T> typeToMock, CreationSettings<T> source)
private static java.util.Set<java.lang.Class<?>> prepareExtraInterfaces(CreationSettings settings)