Mockito 2.25.0 API
Mockito 2.25.0 API
org.mockito
Class Mockito
java.lang.Object
org.mockito.ArgumentMatchers
org.mockito.Mockito
Direct Known Subclasses:
BDDMockito
This javadoc content is also available on the http://mockito.org web page. All documentation is
kept in javadocs because it guarantees consistency between what's on the web and what's in
the source code. It allows access to documentation straight from the IDE even if you work
offline. It motivates Mockito developers to keep documentation up-to-date with the code that
they write, every day, with every commit.
Contents
0. Migrating to Mockito 2
0.1 Mockito Android support
0.2 Configuration-free inline mock making
1. Let's verify some behaviour!
2. How about some stubbing?
3. Argument matchers
4. Verifying exact number of invocations / at least once / never
5. Stubbing void methods with exceptions
6. Verification in order
7. Making sure interaction(s) never happened on mock
8. Finding redundant invocations
9. Shorthand for mocks creation - @Mock annotation
10. Stubbing consecutive calls (iterator-style stubbing)
11. Stubbing with callbacks
12. doReturn()
doReturn()|doThrow()
doThrow()|doAnswer()
doAnswer()|doNothing()
doNothing()|doCallRealMethod()
doCallRealMethod() family of
methods
13. Spying on real objects
14. Changing default return values of unstubbed invocations (Since 1.7)
15. Capturing arguments for further assertions (Since 1.8.0)
16. Real partial mocks (Since 1.8.0)
17. Resetting mocks (Since 1.8.0)
18. Troubleshooting & validating framework usage (Since 1.8.0)
19. Aliases for behavior driven development (Since 1.8.0)
20. Serializable mocks (Since 1.8.1)
21. New annotations: @Captor
@Captor, @Spy
@Spy, @InjectMocks (Since 1.8.3)
22. Verification with timeout (Since 1.8.5)
23. Automatic instantiation of @Spies
@Spies, @InjectMocks and constructor injection
goodness (Since 1.9.0)
24. One-liner stubs (Since 1.9.0)
25. Verification ignoring stubs (Since 1.9.0)
26. Mocking details (Improved in 2.2.x)
27. Delegate calls to real instance (Since 1.9.5)
28. MockMaker API (Since 1.9.5)
29. BDD style verification (Since 1.10.0)
30. Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and
2.7.14)
31. Mockito mocks can be serialized / deserialized across classloaders (Since 1.10.0)
32. Better generic support with deep stubs (Since 1.10.0)
33. Mockito JUnit rule (Since 1.10.17)
34. Switch on or off plugins (Since 1.10.15)
35. Custom verification failure message (Since 2.1.0)
36. Java 8 Lambda Matcher Support (Since 2.1.0)
37. Java 8 Custom Answer Support (Since 2.1.0)
38. Meta data and generic type retention (Since 2.1.0)
39. Mocking final types, enums and final methods (Since 2.1.0)
40. Improved productivity and cleaner tests with "stricter" Mockito (Since 2.+)
41. Advanced public API for framework integrations (Since 2.10.+)
42. New API for integrations: listening on verification start events (Since 2.11.+)
43. New API for integrations: MockitoSession is usable by testing frameworks (Since
2.15.+)
44. Deprecated org.mockito.plugins.InstantiatorProvider as it was leaking
internal API. it was replaced by org.mockito.plugins.InstantiatorProvider2
(Since 2.15.4)
45. New JUnit Jupiter (JUnit5+) extension
46. New Mockito.lenient() and MockSettings.lenient() methods (Since 2.20.0)
47. New API for clearing mock state in inline mocking (Since 2.25.0)
0. Migrating to Mockito 2
In order to continue improving Mockito and further improve the unit testing experience, we
want you to upgrade to 2.1.0! Mockito follows semantic versioning and contains breaking
changes only on major version upgrades. In the lifecycle of a library, breaking changes are
necessary to roll out a set of brand new features that alter the existing behavior or even
change the API. For a comprehensive guide on the new release including incompatible
changes, see 'What's new in Mockito 2' wiki page. We hope that you enjoy Mockito 2!
repositories {
jcenter()
}
dependencies {
testCompile "org.mockito:mockito-core:+"
androidTestCompile "org.mockito:mockito-android:+"
}
You can continue to run the same unit tests on a regular VM by using the `mockito-core`
artifact in your "testCompile" scope as shown above. Be aware that you cannot use the inline
mock maker on Android due to limitations in the Android VM. If you encounter issues with
mocking on Android, please open an issue on the official issue tracker. Do provide the version
of Android you are working on and dependencies of your project.
repositories {
jcenter()
}
dependencies {
testCompile "org.mockito:mockito-inline:+"
}
Be aware that this artifact may be abolished when the inline mock making feature is
integrated into the default mock maker.
For more information about inline mock making, see section 39.
//mock creation
List mockedList = mock(List.class);
//verification
verify(mockedList).add("one");
verify(mockedList).clear();
Once created, a mock will remember all interactions. Then you can selectively verify whatever
interactions you are interested in.
//stubbing
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new
new RuntimeException());
By default, for all methods that return a value, a mock will return either null, a
primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for
an int/Integer and false for a boolean/Boolean.
Stubbing can be overridden: for example common stubbing can go to fixture setup but the
test methods can override it. Please note that overridding stubbing is a potential code
smell that points out too much stubbing
Once stubbed, the method will always return a stubbed value, regardless of how many
times it is called.
Last stubbing is more important - when you stubbed the same method with the same
arguments many times. Other words: the order of stubbing matters but it is only
meaningful rarely, e.g. when stubbing exactly the same method calls or sometimes when
argument matchers are used, etc.
3. Argument matchers
Mockito verifies argument values in natural java style: by using an equals() method.
Sometimes, when extra flexibility is required then you might use argument matchers:
//stubbing using custom matcher (let's say isValid() returns your own mat
when(mockedList.contains(argThat(isValid()))).thenReturn("element");
//you
you can also verify using an argument matcher
verify(mockedList).get(anyInt());
//argument
argument matchers can also be written as Java 8 Lambdas
verify(mockedList).add(argThat(someString -> someString.length() > 5));
Argument matchers allow flexible verification or stubbing. Click here or here to see more
built-in matchers and examples of custom argument matchers / hamcrest matchers.
For information solely on custom argument matchers check out javadoc for
ArgumentMatcher class.
Be reasonable with using complicated argument matching. The natural matching style using
equals() with occasional anyX() matchers tend to give clean & simple tests. Sometimes it's
just better to refactor the code to allow equals() matching or even implement equals()
method to help out with testing.
If you are using argument matchers, all arguments have to be provided by matchers.
The following example shows verification but the same applies to stubbing:
Matcher methods like anyObject(), eq() do not return matchers. Internally, they record a
matcher on a stack and return a dummy value (usually null). This implementation is due to
static type safety imposed by the java compiler. The consequence is that you cannot use
anyObject(), eq() methods outside of verified/stubbed method.
//using mock
mockedList.add("once");
mockedList.add("twice");
mockedList.add("twice");
mockedList.add("three times");
mockedList.add("three times");
mockedList.add("three times");
doThrow(new
new RuntimeException()).when(mockedList).clear();
6. Verification in order
//following will make sure that add is first called with "was added first
inOrder.verify(singleMock).add("was added first");
inOrder.verify(singleMock).add("was added second");
//using mocks
firstMock.add("was called first");
secondMock.add("was called second");
//create inOrder object passing any mocks that need to be verified in ord
InOrder inOrder = inOrder(firstMock, secondMock);
//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).add("was called first");
inOrder.verify(secondMock).add("was called second");
Verification in order is flexible - you don't have to verify all interactions one-by-one but
only those that you are interested in testing in order.
Also, you can create an InOrder object passing only the mocks that are relevant for in-order
verification.
//ordinary verification
verify(mockOne).add("one");
//using mocks
mockedList.add("one");
mockedList.add("two");
verify(mockedList).add("one");
A word of warning: Some users who did a lot of classic, expect-run-verify mocking tend to
use verifyNoMoreInteractions() very often, even in every test method.
verifyNoMoreInteractions() is not recommended to use in every test method.
verifyNoMoreInteractions() is a handy assertion from the interaction testing toolkit. Use
it only when it's relevant. Abusing it leads to overspecified, less maintainable tests.
See also never() - it is more explicit and communicates the intent well.
MockitoAnnotations.initMocks(testClass);
You can use built-in runner: MockitoJUnitRunner or a rule: MockitoRule. For JUnit5 tests,
refer to the JUnit5 extension described in section 45.
when(mock.someMethod("some arg"))
.thenThrow(new
new RuntimeException())
.thenReturn("foo");
when(mock.someMethod("some arg"))
.thenReturn("one", "two", "three");
Warning : if instead of chaining .thenReturn() calls, multiple stubbing with the same
matchers or arguments is used, then each stubbing will override the previous one:
Yet another controversial feature which was not included in Mockito originally. We recommend
simply stubbing with thenReturn() or thenThrow(), which should be enough to test/test-
drive any clean & simple code. However, if you do have a need to stub with the generic
Answer interface, here is an example:
when(mock.someMethod(anyString())).thenAnswer(
new Answer() {
public Object answer
answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return "called with arguments: " + Arrays.toString(args);
}
});
12. doReturn()
doReturn()|doThrow()
doThrow()|
doAnswer()|doNothing()
doAnswer() doNothing()|doCallRealMethod()
doCallRealMethod() family of
methods
Stubbing void methods requires a different approach from when(Object) because the
compiler does not like void methods inside brackets...
Use doThrow() when you want to stub a void method with an exception:
doThrow(new
new RuntimeException()).when(mockedList).clear();
doReturn(Object)
doThrow(Throwable...)
doThrow(Class)
doAnswer(Answer)
doNothing()
doCallRealMethod()
Real spies should be used carefully and occasionally, for example when dealing with
legacy code.
Spying on real objects can be associated with "partial mocking" concept. Before the release
1.8, Mockito spies were not real partial mocks. The reason was we thought partial mock is a
code smell. At some point we found legitimate use cases for partial mocks (3rd party
interfaces, interim refactoring of legacy code).
Mockito *does not* delegate calls to the passed real instance, instead it actually creates a
copy of it. So if you keep the real instance and interact with it, don't expect the spied to be
aware of those interaction and their effect on real instance state. The corollary is that when an
*unstubbed* method is called *on the spy* but *not on the real instance*, you won't see
any effects on the real instance.
Watch out for final methods. Mockito doesn't mock final methods so the bottom line is: when
you spy on real objects + you try to stub a final method = trouble. Also you won't be able to
verify those method as well.
It is the default answer so it will be used only when you don't stub the method call.
Warning: it is recommended to use ArgumentCaptor with verification but not with stubbing.
Using ArgumentCaptor with stubbing may decrease test readability because captor is created
outside of assert (aka verify or 'then') block. Also it may reduce defect localization because if
stubbed method was not called then no argument is captured.
Custom argument matchers via ArgumentMatcher are usually better for stubbing.
Before release 1.8 spy() was not producing real partial mocks and it was confusing for
some users. Read more about spying: here or in javadoc for spy(Object) method.
As usual you are going to read the partial mock warning: Object oriented programming is
more less 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.
Instead of reset() please consider writing simple, small and focused test methods over
lengthy, over-specified tests. First potential code smell is reset() in the middle of the
test method. This probably means you're testing too much. Follow the whisper of your test
methods: "Please keep us small & focused on single behavior". There are several threads
about it on mockito mailing list.
The only reason we added reset() method is to make it possible to work with container-
injected mocks. For more information see FAQ (here).
Don't harm yourself. reset() in the middle of the test method is a code smell (you're
probably testing too much).
reset(mock);
//at this point the mock forgot any interactions & stubbing
Next, you should know that Mockito validates if you use it correctly all the time. However,
there's a gotcha so please read the javadoc for validateMockitoUsage()
The problem is that current stubbing api with canonical role of when word does not integrate
nicely with //given //when //then comments. It's because stubbing belongs to given
component of the test and not to the when component of the test. Hence BDDMockito class
introduces an alias so that you stub method calls with BDDMockito.given(Object) method.
Now it really nicely integrates with the given component of a BDD style test!
//when
Goods goods = shop.buyBread();
//then
assertThat(goods, containBread());
}
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.
The mock can be serialized assuming all the normal serialization requirements are met by the
class.
Making a real object spy serializable is a bit more effort as the spy(...) method does not have
an overloaded version which accepts MockSettings. No worries, you will hardly ever use it.
Note that @InjectMocks can also be used in combination with the @Spy annotation, it
means that Mockito will inject mocks into the partial mock under test. This complexity is
another good reason why you should only use partial mocks as a last resort. See point 16
about partial mocks.
Allows verifying with timeout. It causes a verify to wait for a specified period of time for a
desired interaction rather than fails immediately if had not already happened. May be useful
for testing in concurrent conditions.
This feature should be used rarely - figure out a better way of testing your multi-threaded
system.
Examples:
Mockito will now try to instantiate @Spy and will instantiate @InjectMocks fields using
constructor injection, setter injection, or field injection.
Read more about available tricks and the rules of injection in the javadoc for InjectMocks
//instead:
@Spy BeerDrinker drinker = new BeerDrinker();
//you can write:
@Spy BeerDrinker drinker;
Mockito will now allow you to create mocks when stubbing. Basically, it allows to create a stub
in one line of code. This can be helpful to keep test code clean. For example, some boring
stub can be created & stubbed at field initialization in a test:
Mockito will now allow to ignore stubbing for the sake of verification. Sometimes useful when
coupled with verifyNoMoreInteractions() or verification inOrder(). Helps avoiding
redundant verification of stubbed calls - typically we're not interested in verifying stubs.
Some examples:
verify(mock).foo();
verify(mockTwo).bar();
Advanced examples and more details can be found in javadoc for ignoreStubs(Object...)
Mockito offers API to inspect the details of a mock object. This API is useful for advanced
users and mocking framework integrators.
Useful for spies or partial mocks of objects that are difficult to mock or spy using the usual
spy API. Since Mockito 1.10.11, the delegate may or may not be of the same type as the
mock. If the type is different, a matching method needs to be found on delegate type
otherwise an exception is thrown. Possible use cases for this feature:
The regular spy (spy(Object)) contains all state from the spied instance and the
methods are invoked on the spy. The spied instance is only used at mock creation to copy
the state from. If you call a method on a regular spy and it internally calls other methods
on this spy, those calls are remembered for verifications, and they can be effectively
stubbed.
The mock that delegates simply delegates all methods to the delegate. The delegate is
used all the time as methods are delegated onto it. If you call a method on a mock that
delegates and it internally calls other methods on this mock, those calls are not
remembered for verifications, stubbing does not have effect on them, too. Mock that
delegates is less powerful than the regular spy but it is useful when the regular spy cannot
be created.
Driven by requirements and patches from Google Android guys Mockito now offers an
extension point that allows replacing the proxy generation engine. By default, Mockito uses
Byte Buddy to create dynamic proxies.
The extension point is for advanced users that want to extend Mockito. For example, it is now
possible to use Mockito for Android testing with a help of dexmaker.
For more details, motivations and examples please refer to the docs for MockMaker.
given(dog.bark()).willReturn(2);
// when
...
then(person).should(times(2)).ride(bike);
Previously, spying was only possible on instances of objects. New API makes it possible to
use constructor when creating an instance of the mock. This is particularly useful for mocking
abstract classes because the user is no longer required to provide an instance of the abstract
class. At the moment, only parameter-less constructor is supported, let us know if it is not
enough.
@RunWith(YetAnotherRunner.class)
public class TheTest {
@Rule public MockitoRule mockito = MockitoJUnit.rule();
// ...
}
Examples:
You can use Java 8 lambda expressions with ArgumentMatcher to reduce the dependency
on ArgumentCaptor. If you need to verify that the input to a function call on a mock was
correct, then you would normally use the ArgumentCaptor to find the operands used and
then do subsequent assertions on them. While for complex examples this can be useful, it's
also long-winded.
Writing a lambda to express the match is quite easy. The argument to your function, when
used in conjunction with argThat, will be passed to the ArgumentMatcher as a strongly typed
object, so it is possible to do anything with it.
Examples:
// more complex Java 8 example - where you can specify complex verificati
verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubOb
// this can also be used when defining the behaviour of a mock under diff
// in this case if the input list was fewer than 3 items the mock returns
when(mock.someMethod(argThat(list -> list.size()<3))).thenReturn(null
null);
As the Answer interface has just one method it is already possible to implement it in Java 8
using a lambda expression for very simple situations. The more you need to use the
parameters of the method call, the more you need to typecast the arguments from
InvocationOnMock.
Examples:
For convenience it is possible to write custom answers/actions, which use the parameters to
the method call, as Java 8 lambdas. Even in Java 7 and lower these custom answers based
on a typed interface can reduce boilerplate. In particular, this approach will make it easier to
test functions which use callbacks. The methods answer and answerVoid can be used to
create the answer. They rely on the related answer interfaces in org.mockito.stubbing
that support answers up to 5 parameters.
Examples:
// the example callback has a function and the class under test
// will depend on the callback being invoked
void receive
receive(String item);
// Java 8 - style 1
doAnswer(AdditionalAnswers.answerVoid((operand, callback) -> callback.rec
.when(mock).execute(anyString(), any(Callback.class));
doAnswer(answerVoid(TestClass::dummyCallbackImpl)
.when(mock).execute(anyString(), any(Callback.class));
// Java 7
doAnswer(answerVoid(new
new VoidAnswer2() {
public void answer
answer(String operation, Callback callback) {
callback.receive("dummy");
}})).when(mock).execute(anyString(), any(Callback.class));
// Java 7
doAnswer(answer(new
new Answer2() {
public String answer
answer(String input1, String input2) {
return input1 + input2;
}})).when(mock).execute(anyString(), anyString());
Mockito now preserves annotations on mocked methods and types as well as generic meta
data. Previously, a mock type did not preserve annotations on types unless they were
explicitly inherited and never retained annotations on methods. As a consequence, the
following conditions now hold true:
@MyAnnotation
class Foo {
List<String> bar
bar() { ... }
}
When using Java 8, Mockito now also preserves type annotations. This is default behavior
and might not hold if an alternative MockMaker is used.
39. Mocking final types, enums and final methods (Since 2.1.0)
Mockito now offers an Incubating, optional support for mocking final classes and methods.
This is a fantastic improvement that demonstrates Mockito's everlasting quest for improving
testing experience. Our ambition is that Mockito "just works" with final classes and methods.
Previously they were considered unmockable, preventing the user from mocking. We already
started discussing how to make this feature enabled by default. Currently, the feature is still
optional as we wait for more feedback from the community.
This alternative mock maker which uses a combination of both Java instrumentation API and
sub-classing rather than creating a new class to represent a mock. This way, it becomes
possible to mock final types and methods.
This mock maker is turned off by default because it is based on completely different
mocking mechanism that requires more feedback from the community. It can be activated
explicitly by the mockito extension mechanism, just create in the classpath a file /mockito-
extensions/org.mockito.plugins.MockMaker containing the value mock-maker-
inline.
As a convenience, the Mockito team provides an artifact where this mock maker is
preconfigured. Instead of using the mockito-core artifact, include the mockito-inline artifact in
your project. Note that this artifact is likely to be discontinued once mocking of final classes
and methods gets integrated into the default mock maker.
Mocking final types and enums is incompatible with mock settings like :
This mock maker has been designed around Java Agent runtime attachment ; this require
a compatible JVM, that is part of the JDK (or Java 9 VM). When running on a non-JDK VM
prior to Java 9, it is however possible to manually add the Byte Buddy Java agent jar using
the -javaagent parameter upon starting the JVM.
If you are interested in more details of this feature please read the javadoc of
org.mockito.internal.creation.bytebuddy.InlineByteBuddyMockMaker
Mockito is a "loose" mocking framework by default. Mocks can be interacted with without
setting any expectations beforehand. This is intentional and it improves the quality of tests by
forcing users to be explicit about what they want to stub / verify. It is also very intuitive, easy to
use and blends nicely with "given", "when", "then" template of clean test code. This is also
different from the classic mocking frameworks of the past, they were "strict" by default.
Being "loose" by default makes Mockito tests harder to debug at times. There are scenarios
where misconfigured stubbing (like using a wrong argument) forces the user to run the test
with a debugger. Ideally, tests failures are immediately obvious and don't require debugger to
identify the root cause. Starting with version 2.1 Mockito has been getting new features that
nudge the framework towards "strictness". We want Mockito to offer fantastic debuggability
while not losing its core mocking style, optimized for intuitiveness, explicitness and clean test
code.
Help Mockito! Try the new features, give us feedback, join the discussion about Mockito
strictness at GitHub issue 769.
lenient().when(mock.foo()).thenReturn("ok");
If you want all the stubbings on a given mock to be lenient, you can
configure the mock accordingly:
For more information refer to lenient(). Let us know how do you find the
new feature by opening a GitHub issue to discuss!
Field Summary
Modifier and Type Field and Description
static CALLS_REAL_METHODS
Answer<Object> Optional Answer to be used with mock(Class, Answer)
static RETURNS_DEEP_STUBS
Answer<Object> Optional Answer to be used with mock(Class, Answer).
RETURNS_DEFAULTS
static
The default Answer of every mock if the mock was not
Answer<Object>
stubbed.
static RETURNS_MOCKS
Answer<Object> Optional Answer to be used with mock(Class, Answer)
static RETURNS_SELF
Answer<Object> Optional Answer to be used with mock(Class, Answer).
static RETURNS_SMART_NULLS
Answer<Object> Optional Answer to be used with mock(Class, Answer).
Constructor Summary
Constructor and Description
Mockito()
Method Summary
Modifier and Type Method and Description
after(long millis)
static
Verification will be triggered after given amount
VerificationAfterDelay
of millis, allowing testing of async code.
atLeast(int minNumberOfInvocations)
static VerificationMode
Allows at-least-x verification.
atLeastOnce()
static VerificationMode
Allows at-least-once verification.
atMost(int maxNumberOfInvocations)
static VerificationMode
Allows at-most-x verification.
calls(int wantedNumberOfInvocations)
static VerificationMode
Allows non-greedy verification in order.
clearInvocations(T... mocks)
static <T> void Use this method in order to only clear
invocations, when stubbing is non-trivial.
description(String description)
static VerificationMode Adds a description to be printed if verification
fails.
doAnswer(Answer answer)
static Stubber Use doAnswer() when you want to stub a void
method with generic Answer.
doCallRealMethod()
static Stubber Use doCallRealMethod() when you want to call the
real implementation of a method.
doNothing()
static Stubber Use doNothing() for setting void methods to do
nothing.
doReturn(Object toBeReturned)
static Stubber Use doReturn() in those rare occasions when you
cannot use when(Object).
doReturn(Object toBeReturned,
Object... toBeReturnedNext)
static Stubber
Same as doReturn(Object) but sets consecutive
values to be returned.
doThrow(Class<? extends Throwable> toBeThrown)
static Stubber Use doThrow() when you want to stub the void
method with an exception.
doThrow(Class<? extends Throwable> toBeThrown,
Class<? extends Throwable>... toBeThrownNext)
static Stubber
Same as doThrow(Class) but sets consecutive
exception classes to be thrown.
doThrow(Throwable... toBeThrown)
static Stubber Use doThrow() when you want to stub the void
method with an exception.
framework()
static MockitoFramework
For advanced users or framework integrators.
ignoreStubs(Object... mocks)
static Object[] Ignores stubbed methods of given mocks for the
sake of verification.
inOrder(Object... mocks)
static InOrder Creates InOrder object that allows verifying
mocks in order.
lenient()
static LenientStubber Lenient stubs bypass "strict stubbing" validation
(see Strictness.STRICT_STUBS).
mock(Class<T> classToMock)
static <T> T
Creates mock object of given class or interface.
mock(Class<T> classToMock, Answer defaultAnswer)
static <T> T Creates mock with a specified strategy for its
answers to interactions.
mock(Class<T> classToMock,
static <T> T MockSettings mockSettings)
Creates a mock with some non-standard settings.
mock(Class<T> classToMock, String name)
static <T> T
Specifies mock name.
mockingDetails(Object toInspect)
Returns a MockingDetails instance that enables
static MockingDetails
inspecting a particular object for Mockito
related information.
mockitoSession()
MockitoSession is an optional, highly recommended
static
feature that helps driving cleaner tests by
MockitoSessionBuilder
eliminating boilerplate code and adding extra
validation.
never()
static VerificationMode
Alias to times(0), see times(int)
only()
static VerificationMode Allows checking if given method was the only one
invoked.
reset(T... mocks)
Smart Mockito users hardly use this feature
static <T> void
because they know it could be a sign of poor
tests.
spy(Class<T> classToSpy)
static <T> T
Please refer to the documentation of spy(Object).
spy(T object)
static <T> T
Creates a spy of the real object.
timeout(long millis)
static
Verification will be triggered after given amount
VerificationWithTimeout
of millis, allowing testing of async code.
times(int wantedNumberOfInvocations)
static VerificationMode
Allows verifying exact number of invocations.
validateMockitoUsage()
First of all, in case of any trouble, I encourage
static void
you to read the Mockito FAQ:
https://github.com/mockito/mockito/wiki/FAQ
verify(T mock)
static <T> T
Verifies certain behavior happened once.
once
verify(T mock, VerificationMode mode)
static <T> T Verifies certain behavior happened at least once
/ exact number of times / never.
verifyNoMoreInteractions(Object... mocks)
static void Checks if any of given mocks has any unverified
interaction.
verifyZeroInteractions(Object... mocks)
Verifies that no interactions happened on given
mocks beyond the previously verified
static void
interactions.
This method has the same behavior as
verifyNoMoreInteractions(Object...).
static when(T methodCall)
<T> OngoingStubbing<T> Enables stubbing methods.
withSettings()
static MockSettings Allows mock creation with additional mock
settings.
Field Detail
RETURNS_DEFAULTS
The default Answer of every mock if the mock was not stubbed.
Typically it just returns some empty value.
RETURNS_SMART_NULLS
Example:
RETURNS_MOCKS
RETURNS_DEEP_STUBS
Good quote I've seen one day on the web: every time a mock returns a
mock a fairy dies.
dies
Please note that this answer will return existing mocks that matches
the stub. This behavior is ok with deep stubs and allows verification
to work on the last mock of the chain.
when(mock.getBar(anyString()).getThingy().getName()).thenReturn("d
mock.getBar("candy bar").getThingy().getName();
assertSame(mock.getBar(anyString()).getThingy().getName(), mock.ge
verify(mock.getBar("candy bar").getThingy()).getName();
verify(mock.getBar(anyString()).getThingy()).getName();
Verification only works with the last mock in the chain. You can use
verification modes.
when(person.getAddress(anyString()).getStreet().getName()).thenRet
when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getN
when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getN
person.getAddress("the docks").getStreet().getName();
person.getAddress("the docks").getStreet().getLongName();
person.getAddress("the docks").getStreet(Locale.ITALIAN).getName()
person.getAddress("the docks").getStreet(Locale.CHINESE).getName()
//this:
Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
when(mock.getBar().getName(), "deep");
//is equivalent of
Foo foo = mock(Foo.class);
Bar bar = mock(Bar.class);
when(foo.getBar()).thenReturn(bar);
when(bar.getName()).thenReturn("deep");
This feature will not work when any return type of methods included
in the chain cannot be mocked (for example: is a primitive or a final
class). This is because of java type system.
CALLS_REAL_METHODS
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.
Example:
doReturn(fakeValue).when(mock).getSomething();
RETURNS_SELF
Keep in mind this answer uses the return type of a method. If this
type is assignable to the class of the mock, it will return the mock.
Therefore if you have a method returning a superclass (for example
Object)
Object) it will match and return the mock.
public HttpRequesterWithHeaders
HttpRequesterWithHeaders(HttpBuilder builder) {
this.builder = builder;
this
}
public HttpBuilder
HttpBuilder() {
this.headers = new ArrayList<String>();
this
}
@Test
public void use_full_builder_with_terminating_method
use_full_builder_with_terminating_method() {
HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF);
HttpRequesterWithHeaders requester = new HttpRequesterWithHeade
String response = "StatusCode: 200";
when(builder.request()).thenReturn(response);
assertThat(requester.request("URI")).isEqualTo(response);
}
Constructor Detail
Mockito
public Mockito()
Method Detail
mock
Parameters:
classToMock - class or interface to mock
Returns:
mock object
mock
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.
Parameters:
classToMock - class or interface to mock
name - of the mock
Returns:
mock object
mockingDetails
Parameters:
toInspect - - object to inspect. null input is allowed.
Returns:
A MockingDetails instance.
Since:
1.9.5
mock
It is the default answer so it will be used only when you don't stub
the method call.
Parameters:
classToMock - class or interface to mock
defaultAnswer - default answer for unstubbed methods
Returns:
mock object
mock
Parameters:
classToMock - class or interface to mock
mockSettings - additional mock settings
Returns:
mock object
spy
Creates a spy of the real object. The spy calls real methods unless
they are stubbed.
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.
Example:
Note that the spy won't have any annotations of the spied type,
because CGLIB won't rewrite them. It may troublesome for code that
rely on the spy to have these annotations.
Parameters:
object - to spy on
Returns:
a spy of the real object
spy
@Incubating
public static <T> T spy(Class<T> classToSpy)
Examples:
Type Parameters:
T - type of the spy
Parameters:
classToSpy - the class to spy
Returns:
a spy of the provided class
Since:
1.10.12
when
Enables stubbing methods. Use it when you want the mock to return
particular value when particular method is called.
Examples:
when(mock.someMethod()).thenReturn
when thenReturn(10);
Once stubbed, the method will always return stubbed value regardless
of how many times it is called.
Last stubbing is more important - when you stubbed the same method
with the same arguments many times.
Parameters:
methodCall - method to be stubbed
Returns:
OngoingStubbing object used to stub fluently. Do not create a
reference to this returned object.
verify
verify(mock).someMethod("some arg");
Parameters:
mock - to be verified
Returns:
mock object itself
verify
Parameters:
mock - to be verified
mode - times(x), atLeastOnce() or never()
Returns:
mock object itself
reset
Smart Mockito users hardly use this feature because they know it
could be a sign of poor tests. Normally, you don't need to reset your
mocks, just create new mocks for each test method.
reset(mock);
//at this point the mock forgot any interactions & stubbing
Type Parameters:
T - The Type of the mocks
Parameters:
mocks - to be reset
clearInvocations
Type Parameters:
T - The type of the mocks
Parameters:
mocks - The mocks to clear the invocations for
verifyNoMoreInteractions
You can use this method after you verified your mocks - to make sure
that nothing else was invoked on your mocks.
A word of warning
warning: Some users who did a lot of classic, expect-run-
verify mocking tend to use verifyNoMoreInteractions() very often,
even in every test method. verifyNoMoreInteractions() is not
recommended to use in every test method. verifyNoMoreInteractions()
is a handy assertion from the interaction testing toolkit. Use it
only when it's relevant. Abusing it leads to overspecified, less
maintainable tests.
Example:
//interactions
mock.doSomething();
mock.doSomethingUnexpected();
//verification
verify(mock).doSomething();
Parameters:
mocks - to be verified
verifyZeroInteractions
Parameters:
mocks - to be verified
doThrow
Use doThrow() when you want to stub the void method with an
exception.
Example:
doThrow(new
new RuntimeException()).when(mock).someVoidMethod();
Parameters:
toBeThrown - to be thrown when the stubbed method is called
Returns:
stubber - to select a method for stubbing
doThrow
Use doThrow() when you want to stub the void method with an
exception.
Example:
doThrow(RuntimeException.class).when(mock).someVoidMethod();
Parameters:
toBeThrown - to be thrown when the stubbed method is called
Returns:
stubber - to select a method for stubbing
Since:
2.1.0
doThrow
Example:
doThrow(RuntimeException.class, BigFailure.class).when(mock).someV
Parameters:
toBeThrown - to be thrown when the stubbed method is called
toBeThrownNext - next to be thrown when the stubbed method is
called
Returns:
stubber - to select a method for stubbing
Since:
2.1.0
doCallRealMethod
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.
See also javadoc spy(Object) to find out more about partial mocks.
Mockito.spy() is a recommended way of creating partial mocks. The
reason is it guarantees real methods are called against correctly
constructed object because you're responsible for constructing the
object passed to spy() method.
Example:
Returns:
stubber - to select a method for stubbing
Since:
1.9.5
doAnswer
Use doAnswer() when you want to stub a void method with generic
Answer.
Example:
doAnswer(new
new Answer() {
public Object answer
answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Mock mock = invocation.getMock();
return null
null;
}})
.when(mock).someMethod();
Parameters:
answer - to answer when the stubbed method is called
Returns:
stubber - to select a method for stubbing
doNothing
doNothing().
doThrow(new
new RuntimeException())
.when(mock).someVoidMethod();
When you spy real objects and you want the void method to do nothing:
spy.add("one");
Returns:
stubber - to select a method for stubbing
doReturn
When spying real objects and calling real methods on a spy brings
side effects
when(mock.foo()).thenThrow(new
new RuntimeException());
Parameters:
toBeReturned - to be returned when the stubbed method is called
Returns:
stubber - to select a method for stubbing
doReturn
When spying real objects and calling real methods on a spy brings
side effects
when(mock.foo()).thenThrow(new
new RuntimeException());
Parameters:
toBeReturned - to be returned when the stubbed method is called
toBeReturnedNext - to be returned in consecutive calls when the
stubbed method is called
Returns:
stubber - to select a method for stubbing
Since:
2.1.0
inOrder
Also, you can create InOrder object passing only mocks that are
relevant for in-order verification.
InOrder verification is 'greedy', but you will hardly ever notice it.
If you want to find out more, read this wiki page.
Parameters:
mocks - to be verified in order
Returns:
InOrder object to be used to verify in order
ignoreStubs
Example:
//mocking lists for the sake of the example (if you mock List in re
List mock1 = mock(List.class), mock2 = mock(List.class);
//stubbing mocks:
when(mock1.get(0)).thenReturn(10);
when(mock2.get(0)).thenReturn(20);
//verification:
verify(mock1).clear();
verify(mock2).clear();
list.add(0);
list.clear();
System.out.println(list.get(0)); //we don't want to verify this
list.size();
verify(list).size();
Parameters:
mocks - input mocks that will be changed
Returns:
the same mocks that were passed in as parameters
Since:
1.9.0
times
Parameters:
wantedNumberOfInvocations - wanted number of invocations
Returns:
verification mode
never
verify(mock, never()).someMethod();
If you want to verify there were NO interactions with the mock check
out verifyZeroInteractions(Object...) or
verifyNoMoreInteractions(Object...)
Returns:
verification mode
atLeastOnce
Alias to atLeast(1).
Returns:
verification mode
atLeast
Parameters:
minNumberOfInvocations - minimum number of invocations
Returns:
verification mode
atMost
Parameters:
maxNumberOfInvocations - max number of invocations
Returns:
verification mode
calls
Parameters:
wantedNumberOfInvocations - number of invocations to verify
Returns:
verification mode
only
Allows checking if given method was the only one invoked. E.g:
verify(mock, only()).someMethod();
//above is a shorthand for following 2 lines of code:
verify(mock).someMethod();
verifyNoMoreInvocations(mock);
Returns:
verification mode
timeout
Parameters:
millis - - duration in milliseconds
Returns:
object that allows fluent specification of the verification
(times(x), atLeast(y), etc.)
after
//1.
mock.foo();
verify(mock, after(1000)).foo();
//waits 1000 millis and succeeds
//2.
mock.foo();
verify(mock, timeout(1000)).foo();
//succeeds immediately
Parameters:
millis - - duration in milliseconds
Returns:
object that allows fluent specification of the verification
validateMockitoUsage
withSettings
Don't use it too often. Consider writing simple tests that use simple
mocks. Repeat after me: simple tests push simple, KISSy, readable &
maintainable code. If you cannot write a test in a simple way -
refactor the code under test.
Returns:
mock settings instance with defaults.
description
Parameters:
description - The description to print on failure.
Returns:
verification mode
Since:
2.1.0
framework
@Incubating
public static MockitoFramework framework()
Since:
2.1.0
mockitoSession
@Incubating
public static MockitoSessionBuilder mockitoSession()
For more information, including use cases and sample code, see the
javadoc for MockitoSession.
Since:
2.7.0
lenient
@Incubating
public static LenientStubber lenient()
lenient().when(mock.foo()).thenReturn("ok");
Most mocks in most tests don't need leniency and should happily
prosper with Strictness.STRICT_STUBS.
Elaborate example
In below example, 'foo.foo()' is a stubbing that was moved to
'before()' method to avoid duplication. Doing so makes one of the
test methods ('test3()') fail with 'unnecessary stubbing'. To
resolve it we can configure 'foo.foo()' stubbing in 'before()'
method to be lenient. Alternatively, we can configure entire 'foo'
mock as lenient.
Since:
2.20.0