public interface MockSettings extends Serializable
//Creates mock with different default answer & name
Foo mock = mock(Foo.class, withSettings()
.defaultAnswer(RETURNS_SMART_NULLS)
.name("cool mockie")
);
//Creates mock with different default answer, descriptive name and extra interfaces
Foo mock = mock(Foo.class, withSettings()
.defaultAnswer(RETURNS_SMART_NULLS)
.name("cool mockie")
.extraInterfaces(Bar.class));
MockSettings
has been introduced for two reasons.
Firstly, to make it easy to add another mock setting when the demand comes.
Secondly, to enable combining together different mock settings without introducing zillions of overloaded mock() methods.Modifier and Type | Method and Description |
---|---|
MockSettings |
defaultAnswer(Answer defaultAnswer)
Specifies default answers to interactions.
|
MockSettings |
extraInterfaces(Class<?>... interfaces)
Specifies extra interfaces the mock should implement.
|
MockSettings |
invocationListeners(InvocationListener... listeners)
Registers a listener for method invocations on this mock.
|
MockSettings |
name(String name)
Specifies mock name.
|
MockSettings |
outerInstance(Object outerClassInstance)
Makes it possible to mock non-static inner classes in conjunction with
useConstructor(Object...) . |
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(Object instance)
Specifies the instance to spy on.
|
MockSettings |
stubOnly()
A stub-only mock does not record method
invocations, thus saving memory but
disallowing verification of invocations.
|
MockSettings |
useConstructor(Object... args)
Mockito attempts to use constructor when creating instance of the mock.
|
MockSettings |
verboseLogging()
Enables real-time logging of method invocations on this mock.
|
MockSettings extraInterfaces(Class<?>... interfaces)
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;
interfaces
- extra interfaces the should implement.MockSettings name(String name)
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
- the name of the mock, later used in all verification errorsMockSettings spiedInstance(Object instance)
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);
instance
- to spy onMockSettings defaultAnswer(Answer defaultAnswer)
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
- default answer to be used by mock when not stubbedMockSettings 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());
MockSettings serializable(SerializableMode mode)
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));
mode
- serialization modeMockSettings verboseLogging()
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());
MockSettings invocationListeners(InvocationListener... listeners)
Multiple listeners may be added, but the same object is only added once. The order, in which the listeners are added, is not guaranteed to be the order in which the listeners are notified. Example:
List mockWithListener = mock(List.class, withSettings().invocationListeners(new YourInvocationListener()));
See the listener interface
for more details.listeners
- The invocation listeners to add. May not be null.MockSettings stubOnly()
Example:
List stubOnly = mock(List.class, withSettings().stubOnly());
@Incubating MockSettings useConstructor(Object... args)
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));
args
- The arguments to pass to the constructor. Not passing any arguments means that a parameter-less
constructor will be called@Incubating MockSettings outerInstance(Object outerClassInstance)
useConstructor(Object...)
.
Example:
InnerClass mock = mock(InnerClass.class, withSettings()
.useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));