- Direct Known Subclasses:
BDDMockito

This javadoc content is also available on the https://site.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 20.1 Mockito Android support
0.2 Configuration-free inline mock making
0.3 Explicitly enabling instrumentation for inline mocking (Java 21+)
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()|doThrow()|doAnswer()|doNothing()|doCallRealMethod() family of methods13. Spying on real objects
14. Changing default return values of un-stubbed 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 and 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, @Spy, @InjectMocks (Since 1.8.3) 22. Verification with timeout (Since 1.8.5)
23. Automatic instantiation of
@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)
48. New API for mocking static methods (Since 3.4.0)
49. New API for mocking object construction (Since 3.5.0)
50. Avoiding code generation when restricting mocks to interfaces (Since 3.12.2)
51. New API for marking classes as unmockable (Since 4.1.0)
52. New strictness attribute for @Mock annotation and
MockSettings.strictness() methods (Since 4.6.0)53. Specifying mock maker for individual mocks (Since 4.8.0)
54. Mocking/spying without specifying class (Since 4.10.0)
55. Verification with assertions (Since 5.3.0)
56. Mocking singletons (like Java enums) (Since 5.22.0)
57. Spying on static methods (Since 5.23.0)
58. Suppressing static initializers (Since 5.24.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!0.1. Mockito Android support
With Mockito version 2.6.1 we ship "native" Android support. To enable Android support, add the `mockito-android` library as dependency to your project. This artifact is published to the same Mockito organization and can be imported for Android as follows:Version catalog:
[versions]
mockito = "5.23.0"
[libraries]
mockito = { module = "org.mockito:mockito-core", version.ref = "mockito" }
mockito-android = { module = "org.mockito:mockito-android", version.ref = "mockito" }
App Gradle file:
dependencies {
testImplementation(libs.mockito)
androidTestImplementation(libs.mockito.android)
}
New in Mockito 5.23.0 - Kotlin support! The `mockito-android` artifact now uses
dexmaker-mockito-inline under the hood to provide inline mocking on Android,
which supports mocking of final classes and methods. This means it can mock Kotlin classes without having to mark them as open.
Note this requires Android API 28 (Android P) or higher at runtime. Apps with a lower
minSdk will still compile, but tests will fail if run on an emulator or device with an API level below 28.
Note you must set android:extractNativeLibs="true" in your androidTest/AndroidManifest.xml for the
dexmaker native library to be accessible:
<application android:extractNativeLibs="true" />
Using `mockito-android` in a non-Android environment is unsupported. For JVM tests, use `mockito-core` directly.
0.2. Configuration-free inline mock making
Starting with version 2.7.6, we offer the 'mockito-inline' artifact that enables inline mock making without configuring the MockMaker extension file. To use this, add the `mockito-inline` instead of the `mockito-core` artifact as follows:
repositories {
mavenCentral()
}
dependencies {
testCompile "org.mockito:mockito-inline:+"
}
Be aware that starting from 5.0.0 the inline mock maker became the default mock maker and this
artifact may be abolished in future versions.
For more information about inline mock making, see section 39.
0.3. Explicitly setting up instrumentation for inline mocking (Java 21+)
Starting from Java 21, the JDK restricts the ability of libraries to attach a Java agent to their own JVM. As a result, the inline-mock-maker might not be able to function without an explicit setup to enable instrumentation, and the JVM will always display a warning. The following are examples about how to set up mockito-core as a Java agent, and it may be more appropriate to choose a different approach depending on your project constraints.
To explicitly attach Mockito during test execution, the library's jar file needs to be specified as -javaagent
as an argument to the executing JVM. To enable this in Gradle, the following example adds Mockito to all test
tasks using Kotlin DSL. Using a CommandLineArgumentProvider is recommended by Gradle to ensure task relocatability (documentation):
val mockitoAgent = configurations.create("mockitoAgent")
dependencies {
testImplementation(libs.mockito)
mockitoAgent(libs.mockito) { isTransitive = false }
}
tasks {
test {
jvmArgs.add("-javaagent:${mockitoAgent.asPath}")
}
}
The same can be achieved using Groovy DSL:
configurations {
mockitoAgent
}
dependencies {
testImplementation(libs.mockito)
mockitoAgent(libs.mockito) {
transitive = false
}
}
tasks {
test {
jvmArgumentProviders.add(new CommandLineArgumentProvider() {
-
Field Summary
FieldsModifier and TypeFieldDescriptionOptionalAnswerto be used withmock(Class, Answer)OptionalAnswerto be used withmock(Class, Answer).The defaultAnswerof every mock if the mock was not stubbed.OptionalAnswerto be used withmock(Class, Answer)OptionalAnswerto be used withmock(Class, Answer).OptionalAnswerto be used withmock(Class, Answer). -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic VerificationAfterDelayafter(long millis) Verification will be triggered after given amount of millis, allowing testing of async code.static VerificationModeatLeast(int minNumberOfInvocations) Allows at-least-x verification.static VerificationModeAllows at-least-once verification.static VerificationModeatMost(int maxNumberOfInvocations) Allows at-most-x verification.static VerificationModeAllows at-most-once verification.static VerificationModecalls(int wantedNumberOfInvocations) Allows non-greedy verification in order.static voidClears all mocks, type caches and instrumentations.static <T> voidclearInvocations(T... mocks) Use this method in order to only clear invocations, when stubbing is non-trivial.static VerificationModedescription(String description) Adds a description to be printed if verification fails.static StubberUsedoAnswer()when you want to stub a void method with genericAnswer.static StubberUsedoCallRealMethod()when you want to call the real implementation of a method.static StubberUsedoNothing()for setting void methods to do nothing.static StubberUsedoReturn()in those rare occasions when you cannot usewhen(Object).static StubberSame asdoReturn(Object)but sets consecutive values to be returned.static StubberUsedoThrow()when you want to stub the void method with an exception.static StubberSame asdoThrow(Class)but sets consecutive exception classes to be thrown.static StubberUsedoThrow()when you want to stub the void method with an exception.static MockitoFrameworkFor advanced users or framework integrators.static Object[]ignoreStubs(Object... mocks) Ignores stubbed methods of given mocks for the sake of verification.static InOrderCreatesInOrderobject that allows verifying mocks in order.static LenientStubberlenient()Lenient stubs bypass "strict stubbing" validation (seeStrictness.STRICT_STUBS).static <T> TCreates mock object of given class or interface.static <T> TSpecifies mock name.static <T> Tmock(Class<T> classToMock, MockSettings mockSettings) Creates a mock with some non-standard settings.static <T> TCreates mock with a specified strategy for its answers to interactions.static <T> TCreates a mock object of the requested class or interface with the given name.static <T> Tmock(MockSettings settings, T... reified) Creates a mock object of the requested class or interface with the given settings.static <T> TCreates a mock object of the requested class or interface with the given default answer.static <T> Tmock(T... reified) Creates a mock object of the requested class or interface.static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, Function<MockedConstruction.Context, MockSettings> mockSettingsFactory) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, Function<MockedConstruction.Context, MockSettings> mockSettingsFactory, MockedConstruction.MockInitializer<T> mockInitializer) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockedConstruction.MockInitializer<T> mockInitializer) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockSettings mockSettings) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockSettings mockSettings, MockedConstruction.MockInitializer<T> mockInitializer) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(Function<MockedConstruction.Context, MockSettings> mockSettingsFactory, MockedConstruction.MockInitializer<T> mockInitializer, T... reified) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(Function<MockedConstruction.Context, MockSettings> mockSettingsFactory, T... reified) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(MockedConstruction.MockInitializer<T> mockInitializer, T... reified) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(MockSettings mockSettings, MockedConstruction.MockInitializer<T> mockInitializer, T... reified) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(MockSettings mockSettings, T... reified) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstruction(T... reified) Creates a thread-local mock controller for all constructions of the given class.static <T> MockedConstruction<T> mockConstructionWithAnswer(Class<T> classToMock, Answer defaultAnswer, Answer... additionalAnswers) Creates a thread-local mock controller for all constructions of the given class.static MockingDetailsmockingDetails(Object toInspect) Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.static MockitoSessionBuilderMockitoSessionis an optional, highly recommended feature that drives writing cleaner tests by eliminating boilerplate code and adding extra validation.static <T> MockedSingleton<T> mockSingleton(T instance) Creates a thread-local mock controller for the given singleton instance.static <T> MockedSingleton<T> mockSingleton(T instance, MockSettings mockSettings) Creates a thread-local mock controller for the given singleton instance.static <T> MockedStatic<T> mockStatic(Class<T> classToMock) Creates a thread-local mock controller for all static methods of the given class or interface.static <T> MockedStatic<T> mockStatic(Class<T> classToMock, String name) Creates a thread-local mock controller for all static methods of the given class or interface.static <T> MockedStatic<T> mockStatic(Class<T> classToMock, MockSettings mockSettings) Creates a thread-local mock controller for all static methods of the given class or interface.static <T> MockedStatic<T> mockStatic(Class<T> classToMock, Answer defaultAnswer) Creates a thread-local mock controller for all static methods of the given class or interface.static <T> MockedStatic<T> mockStatic(String name, T... reified) Creates a thread-local mock controller for all static methods of the given class or interface.static <T> MockedStatic<T> mockStatic(MockSettings mockSettings, T... reified) Creates a thread-local mock controller for all static methods of the given class or interface.static <T> MockedStatic<T> mockStatic(Answer defaultAnswer, T... reified) Creates a thread-local mock controller for all static methods of the given class or interface.static <T> MockedStatic<T> mockStatic(T... reified) Creates a thread-local mock controller for all static methods of the given class or interface.static VerificationModenever()Alias totimes(0), seetimes(int)static VerificationModeonly()Allows checking if given method was the only one invoked.static <T> voidreset(T... mocks) Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.static <T> TPlease refer to the documentation ofspy(Object).static <T> Tspy(T object) Creates a spy of the real object.static <T> Tspy(T... reified) Please refer to the documentation ofspy(Class).static <T> MockedStatic<T> Creates a thread-local spy controller for all static methods of the given class or interface.static <T> MockedStatic<T> Creates a thread-local spy controller for all static methods of the given class or interface.static <T> MockedStatic<T> spyStatic(Class<T> classToSpy, MockSettings mockSettings) Creates a thread-local spy controller for all static methods of the given class or interface.static <T> MockedStatic<T> Creates a thread-local spy controller for all static methods of the given class or interface.static <T> MockedStatic<T> spyStatic(MockSettings mockSettings, T... reified) Creates a thread-local spy controller for all static methods of the given class or interface.static <T> MockedStatic<T> spyStatic(T... reified) Creates a thread-local spy controller for all static methods of the given class or interface.static VerificationWithTimeouttimeout(long millis) Verification will be triggered over and over until the given amount of millis, allowing testing of async code.static VerificationModetimes(int wantedNumberOfInvocations) Allows verifying exact number of invocations.static voidFirst of all, in case of any trouble, I encourage you to read the Mockito FAQ: https://github.com/mockito/mockito/wiki/FAQstatic <T> Tverify(T mock) Verifies certain behavior happened once.static <T> Tverify(T mock, VerificationMode mode) Verifies certain behavior happened at least once / exact number of times / never.static voidverifyNoInteractions(Object... mocks) Verifies that no interactions happened on given mocks.static voidverifyNoMoreInteractions(Object... mocks) Checks if any of given mocks has any unverified interaction.static <T> OngoingStubbing<T> when(@Nullable T methodCall) Enables stubbing methods.static MockSettingsAllows mock creation with additional mock settings.Methods inherited from class org.mockito.ArgumentMatchers
any, any, anyBoolean, anyByte, anyChar, anyCollection, anyDouble, anyFloat, anyInt, anyIterable, anyList, anyLong, anyMap, anySet, anyShort, anyString, argThat, assertArg, assertArg, booleanThat, byteThat, charThat, contains, doubleThat, endsWith, eq, eq, eq, eq, eq, eq, eq, eq, eq, floatThat, intThat, isA, isNotNull, isNotNull, isNull, isNull, longThat, matches, matches, notNull, notNull, nullable, refEq, same, shortThat, startsWith
-
Field Details
-
RETURNS_DEFAULTS
The defaultAnswerof every mock if the mock was not stubbed. Typically, it just returns some empty value.Answercan be used to define the return values of un-stubbed invocations.This implementation first tries the global configuration and if there is no global configuration then it will use a default answer that returns zeros, empty collections, nulls, etc.
-
RETURNS_SMART_NULLS
OptionalAnswerto be used withmock(Class, Answer).Answercan be used to define the return values of un-stubbed invocations.This implementation can be helpful when working with legacy code. Un-stubbed methods often return null. If your code uses the object returned by an un-stubbed call, you get a NullPointerException. This implementation of Answer returns SmartNull instead of null.
SmartNullgives nicer exception messages than NPEs, because it points out the line where the un-stubbed method was called. You just click on the stack trace.ReturnsSmartNullsfirst tries to return ordinary values (zeros, empty collections, empty string, etc.) then it tries to return SmartNull. If the return type is final then plainnullis returned.Example:
Foo mock = mock(Foo.class, RETURNS_SMART_NULLS); //calling un-stubbed method here: Stuff stuff = mock.getStuff(); //using object returned by un-stubbed call: stuff.doSomething(); //Above doesn't yield NullPointerException this time! //Instead, SmartNullPointerException is thrown. //Exception's cause links to un-stubbed mock.getStuff() - just click on the stack trace. -
RETURNS_MOCKS
OptionalAnswerto be used withmock(Class, Answer)Answercan be used to define the return values of un-stubbed invocations.This implementation can be helpful when working with legacy code.
ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.) then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain
nullis returned.Note: Since Java 15, abstract enums are declared sealed, which prevents mocking. Attempting to return a mock for such types will throw a
MockitoExceptioninstead of returningnull. You can still return an existing enum literal from a stubbed method call. -
RETURNS_DEEP_STUBS
OptionalAnswerto be used withmock(Class, Answer).Example that shows how deep stub works:
Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS); // note that we're stubbing a chain of methods here: getBar().getName() when(mock.getBar().getName()).thenReturn("deep"); // note that we're chaining method calls: getBar().getName() assertEquals("deep", mock.getBar().getName());WARNING: This feature should rarely be required for regular clean code! Leave it for legacy code. Mocking a mock to return a mock, to return a mock, (...), to return something meaningful hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).
Good quote I've seen one day on the web: every time a mock returns a mock a fairy 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("deep"); mock.getBar("candy bar").getThingy().getName(); assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName()); 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()).thenReturn("deep"); when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep"); when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep"); 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(); // note that we are actually referring to the very last mock in the stubbing chain. InOrder inOrder = inOrder( person.getAddress("the docks").getStreet(), person.getAddress("the docks").getStreet(Locale.CHINESE), person.getAddress("the docks").getStreet(Locale.ITALIAN) ); inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName(); inOrder.verify(person.getAddress("the docks").getStreet()).getLongName(); inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName(); inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();How deep stub work internally?
//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
OptionalAnswerto be used withmock(Class, Answer)Answercan be used to define the return values of un-stubbed invocations.This implementation can be helpful when working with legacy code. When this implementation is used, un-stubbed methods will delegate to the real implementation. This is a way to create a partial mock object that calls real methods by default.
As usual, you are going to read the partial mock warning: Object oriented programming is more-or-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 and well-designed code.
Example:
Foo mock = mock(Foo.class, CALLS_REAL_METHODS); // this calls the real implementation of Foo.getSomething() value = mock.getSomething(); doReturn(fakeValue).when(mock).getSomething(); // now fakeValue is returned value = mock.getSomething();Note 1: Stubbing partial mocks using
when(mock.getSomething()).thenReturn(fakeValue)syntax will call the real method. For partial mock it's recommended to usedoReturnsyntax.Note 2: If the mock is serialized then deserialized, then this answer will not be able to understand generics metadata.
-
RETURNS_SELF
OptionalAnswerto be used withmock(Class, Answer). Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal to the class or a superclass.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
Consider a HttpBuilder used in a HttpRequesterWithHeaders.Object) it will match and return the mock.
The following test will succeedpublic class HttpRequesterWithHeaders { private HttpBuilder builder; public HttpRequesterWithHeaders(HttpBuilder builder) { this.builder = builder; } public String request(String uri) { return builder.withUrl(uri) .withHeader("Content-type: application/json") .withHeader("Authorization: Bearer") .request(); } } private static class HttpBuilder { private String uri; private List<String> headers; public HttpBuilder() { this.headers = new ArrayList<String>(); } public HttpBuilder withUrl(String uri) { this.uri = uri; return this; } public HttpBuilder withHeader(String header) { this.headers.add(header); return this; } public String request() { return uri + headers.toString(); } }@Test public void use_full_builder_with_terminating_method() { HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF); HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder); String response = "StatusCode: 200"; when(builder.request()).thenReturn(response); assertThat(requester.request("URI")).isEqualTo(response); }
-
-
Constructor Details
-
Mockito
public Mockito()
-
-
Method Details
-
mock
Creates a mock object of the requested class or interface.See examples in javadoc for the
Mockitoclass.- Parameters:
reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- the mock object.
- Since:
- 4.10.0
-
mock
Creates a mock object of the requested class or interface with the given default answer.See examples in javadoc for the
Mockitoclass.- Parameters:
defaultAnswer- the default answer to use.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- the mock object.
- Since:
- 5.1.0
-
mock
Creates a mock object of the requested class or interface with the given name.See examples in javadoc for the
Mockitoclass.- Parameters:
name- the mock name to use.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- the mock object.
- Since:
- 5.1.0
-
mock
Creates a mock object of the requested class or interface with the given settings.See examples in javadoc for the
Mockitoclass.- Parameters:
settings- the mock settings to use.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- the mock object.
- Since:
- 5.1.0
-
mock
Creates mock object of given class or interface.See examples in javadoc for
Mockitoclass- 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
@Mockannotation then you've got naming mocks for free!@Mockuses field name as mock name.Read more.See examples in javadoc for
Mockitoclass- Parameters:
classToMock- class or interface to mockname- of the mock- Returns:
- mock object
-
mockingDetails
Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information. Can be used to find out if given object is a Mockito mock or to find out if a given mock is a spy or mock.In future Mockito versions MockingDetails may grow and provide other useful information about the mock, e.g. invocations, stubbing info, etc.
- Parameters:
toInspect- - object to inspect. null input is allowed.- Returns:
- A
MockingDetailsinstance. - Since:
- 1.9.5
-
mock
Creates mock with a specified strategy for its answers to interactions. It's quite an 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, RETURNS_SMART_NULLS); Foo mockTwo = mock(Foo.class, new YourOwnAnswer());See examples in javadoc for
Mockitoclass- Parameters:
classToMock- class or interface to mockdefaultAnswer- default answer for un-stubbed methods- Returns:
- mock object
-
mock
Creates a mock with some non-standard settings.The number of configuration points for a mock will grow, so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods. Hence
MockSettings.
Use it carefully and occasionally. What might be reason your test needs non-standard mocks? Is the code under test so complicated that it requires non-standard mocks? Wouldn't you prefer to refactor the code under test, so that it is testable in a simple way?Listener mock = mock(Listener.class, withSettings() .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); );See also
withSettings()See examples in javadoc for
Mockitoclass- Parameters:
classToMock- class or interface to mockmockSettings- additional mock settings- Returns:
- mock object
-
spy
public static <T> T spy(T object) Creates a spy of the real object. The spy calls real methods unless they are stubbed.Real spies should be used carefully and occasionally, for example when dealing with legacy code.
As usual, you are going to read the partial mock warning: Object oriented programming tackles 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 and well-designed code.
Example:
List list = new LinkedList(); List spy = spy(list); //optionally, you can stub out some methods: when(spy.size()).thenReturn(100); //using the spy calls real methods spy.add("one"); spy.add("two"); //prints "one" - the first element of a list System.out.println(spy.get(0)); //size() method was stubbed - 100 is printed System.out.println(spy.size()); //optionally, you can verify verify(spy).add("one"); verify(spy).add("two");Important gotcha on spying real objects!
- Sometimes it's impossible or impractical to use
when(Object)for stubbing spies. Therefore for spies it is recommended to always usedoReturn|Answer|Throw()|CallRealMethodfamily of methods for stubbing. 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); - 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 *un-stubbed* 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.
See examples in javadoc for
MockitoclassNote 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
- Sometimes it's impossible or impractical to use
-
spy
Please refer to the documentation ofspy(Object). Overusing spies hints at code design smells.This method, in contrast to the original
spy(Object), creates a spy based on class instead of an object. Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object. This is particularly useful for spying on abstract classes because they cannot be instantiated. See alsoMockSettings.useConstructor(Object...).Examples:
SomeAbstract spy = spy(SomeAbstract.class); //Robust API, via settings builder: OtherAbstract spy = mock(OtherAbstract.class, withSettings() .useConstructor().defaultAnswer(CALLS_REAL_METHODS)); //Mocking a non-static inner abstract class: InnerAbstract spy = mock(InnerAbstract.class, withSettings() .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));- Type Parameters:
T- type of the spy- Parameters:
classToSpy- the class to spy- Returns:
- a spy of the provided class
- Since:
- 1.10.12
-
spy
Please refer to the documentation ofspy(Class).- Parameters:
reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- spy object
- Since:
- 4.10.0
-
mockStatic
Creates a thread-local mock controller for all static methods of the given class or interface. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Parameters:
classToMock- class or interface of which static mocks should be mocked.- Returns:
- mock controller
-
mockStatic
Creates a thread-local mock controller for all static methods of the given class or interface. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Parameters:
classToMock- class or interface of which static mocks should be mocked.defaultAnswer- the default answer when invoking static methods.- Returns:
- mock controller
-
mockStatic
Creates a thread-local mock controller for all static methods of the given class or interface. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Parameters:
classToMock- class or interface of which static mocks should be mocked.name- the name of the mock to use in error messages.- Returns:
- mock controller
-
mockStatic
Creates a thread-local mock controller for all static methods of the given class or interface. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Parameters:
classToMock- class or interface of which static mocks should be mocked.mockSettings- the settings to use where only name and default answer are considered.- Returns:
- mock controller
-
mockStatic
Creates a thread-local mock controller for all static methods of the given class or interface. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Parameters:
reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockStatic
Creates a thread-local mock controller for all static methods of the given class or interface. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Parameters:
defaultAnswer- the default answer when invoking static methods.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockStatic
Creates a thread-local mock controller for all static methods of the given class or interface. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Parameters:
name- the name of the mock to use in error messages.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockStatic
Creates a thread-local mock controller for all static methods of the given class or interface. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.Note: We recommend against mocking static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the mocked class. A mock maker might forbid mocking static methods of know classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Parameters:
mockSettings- the settings to use where only name and default answer are considered.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockSingleton
Creates a thread-local mock controller for the given singleton instance. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.This is useful for mocking instances of objects for which you don't control initialization, assignment, or access to the object, e.g. Java enum values.
See examples in javadoc for
Mockitoclass- Type Parameters:
T- the type of the singleton.- Parameters:
instance- the singleton instance to mock.- Returns:
- mock controller
- Since:
- 5.22.0
-
spyStatic
Creates a thread-local spy controller for all static methods of the given class or interface. Real static methods are called by default unless explicitly stubbed. The returned object'sScopedMock.close()method must be called upon completing the test or the spy will remain active on the current thread.This is the static equivalent of
spy(Object)- it usesAnswers.CALLS_REAL_METHODSas the default answer.Note: We recommend against spying on static methods of classes in the standard library or classes used by custom class loaders used to execute the block with the spied class. A mock maker might forbid mocking static methods of known classes that are known to cause problems. Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not explicitly forbidden.
See examples in javadoc for
Mockitoclass- Type Parameters:
T- the type of the class to spy on.- Parameters:
classToSpy- class or interface of which static methods should be spied on.- Returns:
- spy controller
- Since:
- 5.23.0
-
spyStatic
Creates a thread-local spy controller for all static methods of the given class or interface. Real static methods are called by default unless explicitly stubbed. The returned object'sScopedMock.close()method must be called upon completing the test or the spy will remain active on the current thread.This is the static equivalent of
spy(Object)- it usesAnswers.CALLS_REAL_METHODSas the default answer.See examples in javadoc for
Mockitoclass- Type Parameters:
T- the type of the class to spy on.- Parameters:
classToSpy- class or interface of which static methods should be spied on.name- the name of the spy to use in error messages.- Returns:
- spy controller
- Since:
- 5.23.0
-
spyStatic
Creates a thread-local spy controller for all static methods of the given class or interface. Real static methods are called by default unless explicitly stubbed. The returned object'sScopedMock.close()method must be called upon completing the test or the spy will remain active on the current thread.Note: The default answer will always be overridden to
Answers.CALLS_REAL_METHODS, regardless of any default answer configured in the provided settings.See examples in javadoc for
Mockitoclass- Type Parameters:
T- the type of the class to spy on.- Parameters:
classToSpy- class or interface of which static methods should be spied on.mockSettings- the settings to use where only name is considered (default answer is forced toAnswers.CALLS_REAL_METHODS).- Returns:
- spy controller
- Since:
- 5.23.0
-
spyStatic
Creates a thread-local spy controller for all static methods of the given class or interface. Real static methods are called by default unless explicitly stubbed. The returned object'sScopedMock.close()method must be called upon completing the test or the spy will remain active on the current thread.See examples in javadoc for
Mockitoclass- Type Parameters:
T- the type of the class to spy on.- Parameters:
reified- don't pass any values to it. It's a trick to detect the class/interface you want to spy on.- Returns:
- spy controller
- Since:
- 5.23.0
-
spyStatic
Creates a thread-local spy controller for all static methods of the given class or interface. Real static methods are called by default unless explicitly stubbed. The returned object'sScopedMock.close()method must be called upon completing the test or the spy will remain active on the current thread.See examples in javadoc for
Mockitoclass- Type Parameters:
T- the type of the class to spy on.- Parameters:
name- the name of the spy to use in error messages.reified- don't pass any values to it. It's a trick to detect the class/interface you want to spy on.- Returns:
- spy controller
- Since:
- 5.23.0
-
spyStatic
Creates a thread-local spy controller for all static methods of the given class or interface. Real static methods are called by default unless explicitly stubbed. The returned object'sScopedMock.close()method must be called upon completing the test or the spy will remain active on the current thread.Note: The default answer will always be overridden to
Answers.CALLS_REAL_METHODS, regardless of any default answer configured in the provided settings.See examples in javadoc for
Mockitoclass- Type Parameters:
T- the type of the class to spy on.- Parameters:
mockSettings- the settings to use where only name is considered (default answer is forced toAnswers.CALLS_REAL_METHODS).reified- don't pass any values to it. It's a trick to detect the class/interface you want to spy on.- Returns:
- spy controller
- Since:
- 5.23.0
-
mockSingleton
Creates a thread-local mock controller for the given singleton instance. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.This is useful for mocking instances of objects for which you don't control initialization, assignment, or access to the object, e.g. Java enum values.
See examples in javadoc for
Mockitoclass- Type Parameters:
T- the type of the singleton.- Parameters:
instance- the singleton instance to mock.mockSettings- the mock settings to use.- Returns:
- mock controller
- Since:
- 5.22.0
-
mockConstructionWithAnswer
public static <T> MockedConstruction<T> mockConstructionWithAnswer(Class<T> classToMock, Answer defaultAnswer, Answer... additionalAnswers) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
classToMock- non-abstract class of which constructions should be mocked.defaultAnswer- the default answer for the first created mock.additionalAnswers- the default answer for all additional mocks. For any access mocks, the last answer is used. If this array is empty, thedefaultAnsweris used.- Returns:
- mock controller
-
mockConstruction
Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
classToMock- non-abstract class of which constructions should be mocked.- Returns:
- mock controller
-
mockConstruction
public static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockedConstruction.MockInitializer<T> mockInitializer) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
classToMock- non-abstract class of which constructions should be mocked.mockInitializer- a callback to prepare the methods on a mock after its instantiation.- Returns:
- mock controller
-
mockConstruction
public static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockSettings mockSettings) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
classToMock- non-abstract class of which constructions should be mocked.mockSettings- the mock settings to use.- Returns:
- mock controller
-
mockConstruction
public static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, Function<MockedConstruction.Context, MockSettings> mockSettingsFactory) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
classToMock- non-abstract class of which constructions should be mocked.mockSettingsFactory- the mock settings to use.- Returns:
- mock controller
-
mockConstruction
public static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockSettings mockSettings, MockedConstruction.MockInitializer<T> mockInitializer) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
classToMock- non-abstract class of which constructions should be mocked.mockSettings- the settings to use.mockInitializer- a callback to prepare the methods on a mock after its instantiation.- Returns:
- mock controller
-
mockConstruction
public static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, Function<MockedConstruction.Context, MockSettings> mockSettingsFactory, MockedConstruction.MockInitializer<T> mockInitializer) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
classToMock- non-abstract class of which constructions should be mocked.mockSettingsFactory- a function to create settings to use.mockInitializer- a callback to prepare the methods on a mock after its instantiation.- Returns:
- mock controller
-
mockConstruction
Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockConstruction
@SafeVarargs public static <T> MockedConstruction<T> mockConstruction(MockedConstruction.MockInitializer<T> mockInitializer, T... reified) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
mockInitializer- a callback to prepare the methods on a mock after its instantiation.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockConstruction
@SafeVarargs public static <T> MockedConstruction<T> mockConstruction(MockSettings mockSettings, T... reified) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
mockSettings- the mock settings to use.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockConstruction
@SafeVarargs public static <T> MockedConstruction<T> mockConstruction(Function<MockedConstruction.Context, MockSettings> mockSettingsFactory, T... reified) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
mockSettingsFactory- the mock settings to use.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockConstruction
@SafeVarargs public static <T> MockedConstruction<T> mockConstruction(MockSettings mockSettings, MockedConstruction.MockInitializer<T> mockInitializer, T... reified) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
mockSettings- the settings to use.mockInitializer- a callback to prepare the methods on a mock after its instantiation.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
mockConstruction
@SafeVarargs public static <T> MockedConstruction<T> mockConstruction(Function<MockedConstruction.Context, MockSettings> mockSettingsFactory, MockedConstruction.MockInitializer<T> mockInitializer, T... reified) Creates a thread-local mock controller for all constructions of the given class. The returned object'sScopedMock.close()method must be called upon completing the test or the mock will remain active on the current thread.See examples in javadoc for
Mockitoclass- Parameters:
mockSettingsFactory- a function to create settings to use.mockInitializer- a callback to prepare the methods on a mock after its instantiation.reified- don't pass any values to it. It's a trick to detect the class/interface you want to mock.- Returns:
- mock controller
- Since:
- 5.21.0
-
when
Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.Simply put: "When the x method is called then return y".
Examples:
For stubbing void methods with throwables see:when(mock.someMethod()).thenReturn(10); //you can use flexible argument matchers, e.g: when(mock.someMethod(anyString())).thenReturn(10); //setting exception to be thrown: when(mock.someMethod("some arg")).thenThrow(new RuntimeException()); //you can set different behavior for consecutive method calls. //Last stubbing (e.g: thenReturn("foo")) determines the behavior of further consecutive calls. when(mock.someMethod("some arg")) .thenThrow(new RuntimeException()) .thenReturn("foo"); //Alternative, shorter version for consecutive stubbing: when(mock.someMethod("some arg")) .thenReturn("one", "two"); //is the same as: when(mock.someMethod("some arg")) .thenReturn("one") .thenReturn("two"); //shorter version for consecutive method calls throwing exceptions: when(mock.someMethod("some arg")) .thenThrow(new RuntimeException(), new NullPointerException();doThrow(Throwable...)Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that overriding stubbing is a potential code smell that points out too much stubbing.
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.
Although it is possible to verify a stubbed invocation, usually it's just redundant. Let's say you've stubbed
foo.bar(). If your code cares whatfoo.bar()returns then something else breaks(often before evenverify()gets executed). If your code doesn't care whatget(0)returns then it should not be stubbed.See examples in javadoc for
Mockitoclass- Parameters:
methodCall- method to be stubbed- Returns:
- OngoingStubbing object used to stub fluently. Do not create a reference to this returned object.
-
verify
public static <T> T verify(T mock) Verifies certain behavior happened once.Alias to
verify(mock, times(1))E.g:
Above is equivalent to:verify(mock).someMethod("some arg");verify(mock, times(1)).someMethod("some arg");Arguments passed are compared using
equals()method. Read aboutArgumentCaptororArgumentMatcherto find out other ways of matching / asserting arguments passed.Although it is possible to verify a stubbed invocation, usually it's just redundant. Let's say you've stubbed
foo.bar(). If your code cares whatfoo.bar()returns then something else breaks(often before evenverify()gets executed). If your code doesn't care whatfoo.bar()returns then it should not be stubbed.See examples in javadoc for
Mockitoclass- Parameters:
mock- to be verified- Returns:
- mock object itself
-
verify
Verifies certain behavior happened at least once / exact number of times / never. E.g:
times(1) is the default and can be omittedverify(mock, times(5)).someMethod("was called five times"); verify(mock, atLeast(2)).someMethod("was called at least two times"); //you can use flexible argument matchers, e.g: verify(mock, atLeastOnce()).someMethod(anyString());Arguments passed are compared using
equals()method. Read aboutArgumentCaptororArgumentMatcherto find out other ways of matching / asserting arguments passed.- Parameters:
mock- to be verifiedmode- times(x), atLeastOnce() or never()- Returns:
- mock object itself
-
reset
public static <T> void reset(T... mocks) 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.Instead of
#reset()please consider writing simple, small and focused test methods over lengthy, over-specified tests. First potential code smell isreset()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 and 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 the FAQ (here).Don't harm yourself.
reset()in the middle of the test method is a code smell (you're probably testing too much).List mock = mock(List.class); when(mock.size()).thenReturn(10); mock.add(1); reset(mock); //at this point the mock forgot any interactions and stubbing- Type Parameters:
T- The Type of the mocks- Parameters:
mocks- to be reset
-
clearAllCaches
public static void clearAllCaches()Clears all mocks, type caches and instrumentations.By clearing Mockito's state, previously created mocks might begin to malfunction. This option can be used if Mockito's caches take up too much space or if the inline mock maker's instrumentation is causing performance issues in code where mocks are no longer used. Normally, you would not need to use this option.
-
clearInvocations
public static <T> void clearInvocations(T... mocks) Use this method in order to only clear invocations, when stubbing is non-trivial. Use-cases can be:- You are using a dependency injection framework to inject your mocks.
- The mock is used in a stateful scenario. For example a class is Singleton which depends on your mock.
- Type Parameters:
T- The type of the mocks- Parameters:
mocks- The mocks to clear the invocations for
-
verifyNoMoreInteractions
Checks if any of given mocks has any unverified interaction.You can use this method after you verified your mocks - to make sure that nothing else was invoked on your mocks.
See also
never()- it is more explicit and communicates the intent well.Stubbed invocations (if called) are also treated as interactions. If you want stubbed invocations automatically verified, check out
Strictness.STRICT_STUBSfeature introduced in Mockito 2.3.0. If you want to ignore stubs for verification, seeignoreStubs(Object...).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 over-specified, less maintainable tests.This method will also detect unverified invocations that occurred before the test method, for example: in
setUp(),@Beforemethod or in constructor. Consider writing nice code that makes interactions only in test methods.Example:
See examples in javadoc for//interactions mock.doSomething(); mock.doSomethingUnexpected(); //verification verify(mock).doSomething(); //following will fail because 'doSomethingUnexpected()' is unexpected verifyNoMoreInteractions(mock);Mockitoclass- Parameters:
mocks- to be verified
-
verifyNoInteractions
Verifies that no interactions happened on given mocks.
This method will also detect invocations that occurred before the test method, for example: inverifyNoInteractions(mockOne, mockTwo);setUp(),@Beforemethod or in constructor. Consider writing nice code that makes interactions only in test methods.See also
never()- it is more explicit and communicates the intent well.See examples in javadoc for
Mockitoclass- Parameters:
mocks- to be verified- Since:
- 3.0.1
-
doThrow
UsedoThrow()when you want to stub the void method with an exception.Stubbing voids requires different approach from
when(Object)because the compiler does not like void methods inside brackets...Example:
doThrow(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
UsedoThrow()when you want to stub the void method with an exception.A new exception instance will be created for each method invocation.
Stubbing voids requires different approach from
when(Object)because the compiler does not like void methods inside brackets...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
public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext) Same asdoThrow(Class)but sets consecutive exception classes to be thrown. Remember to usedoThrow()when you want to stub the void method to throw several exceptions that are instances of the specified class.A new exception instance will be created for each method invocation.
Stubbing voids requires different approach from
when(Object)because the compiler does not like void methods inside brackets...Example:
doThrow(RuntimeException.class, BigFailure.class).when(mock).someVoidMethod();- Parameters:
toBeThrown- to be thrown when the stubbed method is calledtoBeThrownNext- next to be thrown when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
- Since:
- 2.1.0
-
doCallRealMethod
UsedoCallRealMethod()when you want to call the real implementation of a method.As usual, you are going to read the partial mock warning: Object oriented programming is more-or-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 and 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:
Foo mock = mock(Foo.class); doCallRealMethod().when(mock).someVoidMethod(); // this will call the real implementation of Foo.someVoidMethod() mock.someVoidMethod();See examples in javadoc for
Mockitoclass- Returns:
- stubber - to select a method for stubbing
- Since:
- 1.9.5
-
doAnswer
UsedoAnswer()when you want to stub a void method with genericAnswer.Stubbing voids requires different approach from
when(Object)because the compiler does not like void methods inside brackets...Example:
doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); Mock mock = invocation.getMock(); return null; }}) .when(mock).someMethod();See examples in javadoc for
Mockitoclass- Parameters:
answer- to answer when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
-
doNothing
UsedoNothing()for setting void methods to do nothing. Beware that void methods on mocks do nothing by default! However, there are rare situations when doNothing() comes handy:- Stubbing consecutive calls on a void method:
doNothing(). doThrow(new RuntimeException()) .when(mock).someVoidMethod(); //does nothing the first time: mock.someVoidMethod(); //throws RuntimeException the next time: mock.someVoidMethod(); - When you spy real objects and you want the void method to do nothing:
List list = new LinkedList(); List spy = spy(list); //let's make clear() do nothing doNothing().when(spy).clear(); spy.add("one"); //clear() does nothing, so the list still contains "one" spy.clear();
See examples in javadoc for
Mockitoclass- Returns:
- stubber - to select a method for stubbing
- Stubbing consecutive calls on a void method:
-
doReturn
UsedoReturn()in those rare occasions when you cannot usewhen(Object).Beware that
when(Object)is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).Here are those rare occasions when doReturn() comes handy:
- When spying real objects and calling real methods on a spy brings side effects
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); - Overriding a previous exception-stubbing:
when(mock.foo()).thenThrow(new RuntimeException()); //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. when(mock.foo()).thenReturn("bar"); //You have to use doReturn() for stubbing: doReturn("bar").when(mock).foo();
See examples in javadoc for
Mockitoclass- Parameters:
toBeReturned- to be returned when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
- When spying real objects and calling real methods on a spy brings side effects
-
doReturn
Same asdoReturn(Object)but sets consecutive values to be returned. Remember to usedoReturn()in those rare occasions when you cannot usewhen(Object).Beware that
when(Object)is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).Here are those rare occasions when doReturn() comes handy:
- When spying real objects and calling real methods on a spy brings side effects
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", "bar", "qix"); //You have to use doReturn() for stubbing: doReturn("foo", "bar", "qix").when(spy).get(0); - Overriding a previous exception-stubbing:
when(mock.foo()).thenThrow(new RuntimeException()); //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. when(mock.foo()).thenReturn("bar", "foo", "qix"); //You have to use doReturn() for stubbing: doReturn("bar", "foo", "qix").when(mock).foo();
See examples in javadoc for
Mockitoclass- Parameters:
toBeReturned- to be returned when the stubbed method is calledtoBeReturnedNext- to be returned in consecutive calls when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
- Since:
- 2.1.0
- When spying real objects and calling real methods on a spy brings side effects
-
inOrder
CreatesInOrderobject that allows verifying mocks in order.
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.InOrder inOrder = inOrder(firstMock, secondMock); inOrder.verify(firstMock).add("was called first"); inOrder.verify(secondMock).add("was called second");Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
InOrderverification is 'greedy', but you will hardly ever notice it. If you want to find out more, read this wiki page.As of Mockito 1.8.4 you can verifyNoMoreInteractions() in order-sensitive way. Read more:
InOrder.verifyNoMoreInteractions()See examples in javadoc for
Mockitoclass- Parameters:
mocks- to be verified in order- Returns:
- InOrder object to be used to verify in order
-
ignoreStubs
Ignores stubbed methods of given mocks for the sake of verification. Please consider usingStrictness.STRICT_STUBSfeature which eliminates the need forignoreStubs()and provides other benefits.ignoreStubs()is sometimes useful when coupled withverifyNoMoreInteractions()or verificationinOrder(). Helps to avoid redundant verification of stubbed calls - typically we're not interested in verifying stubs.Warning,
ignoreStubs()might lead to overuse ofverifyNoMoreInteractions(ignoreStubs(...));Bear in mind that Mockito does not recommend bombarding every test withverifyNoMoreInteractions()for the reasons outlined in javadoc forverifyNoMoreInteractions(Object...)Other words: all *stubbed* methods of given mocks are marked *verified* so that they don't get in a way during verifyNoMoreInteractions().This method changes the input mocks! This method returns input mocks just for convenience.
Ignored stubs will also be ignored for verification inOrder, including
InOrder.verifyNoMoreInteractions(). See the second example.Example:
Ignoring stubs can be used with verification in order://mocking lists for the sake of the example (if you mock List in real you will burn in hell) List mock1 = mock(List.class), mock2 = mock(List.class); //stubbing mocks: when(mock1.get(0)).thenReturn(10); when(mock2.get(0)).thenReturn(20); //using mocks by calling stubbed get(0) methods: System.out.println(mock1.get(0)); //prints 10 System.out.println(mock2.get(0)); //prints 20 //using mocks by calling clear() methods: mock1.clear(); mock2.clear(); //verification: verify(mock1).clear(); verify(mock2).clear(); //verifyNoMoreInteractions() fails because get() methods were not accounted for. try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e); //However, if we ignore stubbed methods then we can verifyNoMoreInteractions() verifyNoMoreInteractions(ignoreStubs(mock1, mock2)); //Remember that ignoreStubs() *changes* the input mocks and returns them for convenience.
Stubbed invocations are automatically verified withList list = mock(List.class); when(list.get(0)).thenReturn("foo"); list.add(0); list.clear(); System.out.println(list.get(0)); //we don't want to verify this InOrder inOrder = inOrder(ignoreStubs(list)); inOrder.verify(list).add(0); inOrder.verify(list).clear(); inOrder.verifyNoMoreInteractions();Strictness.STRICT_STUBSfeature and it eliminates the need forignoreStubs(). Example below uses JUnit Rules:@Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); List list = mock(List.class); when(list.get(0)).thenReturn("foo"); list.size(); verify(list).size(); list.get(0); // Automatically verified by STRICT_STUBS verifyNoMoreInteractions(list); // No need of ignoreStubs()- Parameters:
mocks- input mocks that will be changed- Returns:
- the same mocks that were passed in as parameters
- Since:
- 1.9.0
-
times
Allows verifying exact number of invocations. E.g:
See examples in javadoc forverify(mock, times(2)).someMethod("some arg");Mockitoclass- Parameters:
wantedNumberOfInvocations- wanted number of invocations- Returns:
- verification mode
-
never
Alias totimes(0), seetimes(int)Verifies that interaction did not happen. E.g:
verify(mock, never()).someMethod();If you want to verify there were NO interactions with the mock check out
verifyNoMoreInteractions(Object...)See examples in javadoc for
Mockitoclass- Returns:
- verification mode
-
atLeastOnce
Allows at-least-once verification. E.g:
Alias toverify(mock, atLeastOnce()).someMethod("some arg");atLeast(1).See examples in javadoc for
Mockitoclass- Returns:
- verification mode
-
atLeast
Allows at-least-x verification. E.g:
See examples in javadoc forverify(mock, atLeast(3)).someMethod("some arg");Mockitoclass- Parameters:
minNumberOfInvocations- minimum number of invocations- Returns:
- verification mode
-
atMostOnce
Allows at-most-once verification. E.g:
Alias toverify(mock, atMostOnce()).someMethod("some arg");atMost(1).See examples in javadoc for
Mockitoclass- Returns:
- verification mode
-
atMost
Allows at-most-x verification. E.g:
See examples in javadoc forverify(mock, atMost(3)).someMethod("some arg");Mockitoclass- Parameters:
maxNumberOfInvocations- max number of invocations- Returns:
- verification mode
-
calls
Allows non-greedy verification in order. For exampleinOrder.verify( mock, calls( 2 )).someMethod( "some arg" );- will not fail if the method is called 3 times, unlike times( 2 )
- will not mark the third invocation as verified, unlike atLeast( 2 )
- 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(); verifyNoMoreInteractions(mock);See also
verifyNoMoreInteractions(Object...)See examples in javadoc for
Mockitoclass- Returns:
- verification mode
-
timeout
Verification will be triggered over and over until the given amount of millis, allowing testing of async code. Useful when interactions with the mock object did not happened yet. Extensive use oftimeout()method can be a code smell - there are better ways of testing concurrent code.See also
after(long)method for testing async code. Differences betweentimeout()andafterare explained in Javadoc forafter(long).
See examples in javadoc for//passes when someMethod() is called no later than within 100 ms //exits immediately when verification is satisfied (e.g. may not wait full 100 ms) verify(mock, timeout(100)).someMethod(); //above is an alias to: verify(mock, timeout(100).times(1)).someMethod(); //passes as soon as someMethod() has been called 2 times under 100 ms verify(mock, timeout(100).times(2)).someMethod(); //equivalent: this also passes as soon as someMethod() has been called 2 times under 100 ms verify(mock, timeout(100).atLeast(2)).someMethod();Mockitoclass- Parameters:
millis- - duration in milliseconds- Returns:
- object that allows fluent specification of the verification (times(x), atLeast(y), etc.)
-
after
Verification will be triggered after given amount of millis, allowing testing of async code. Useful when interactions with the mock object have yet to occur. Extensive use ofafter()method can be a code smell - there are better ways of testing concurrent code.Not yet implemented to work with InOrder verification.
See also
timeout(long)method for testing async code. Differences betweentimeout()andafter()are explained below.
timeout() vs. after()//passes after 100ms, if someMethod() has only been called once at that time. verify(mock, after(100)).someMethod(); //above is an alias to: verify(mock, after(100).times(1)).someMethod(); //passes if someMethod() is called *exactly* 2 times, as tested after 100 millis verify(mock, after(100).times(2)).someMethod(); //passes if someMethod() has not been called, as tested after 100 millis verify(mock, after(100).never()).someMethod(); //verifies someMethod() after a given time span using given verification mode //useful only if you have your own custom verification modes. verify(mock, new After(100, yourOwnVerificationMode)).someMethod();- timeout() exits immediately with success when verification passes
- after() awaits full duration to check if verification passes
See examples in javadoc for//1. mock.foo(); verify(mock, after(1000)).foo(); //waits 1000 millis and succeeds //2. mock.foo(); verify(mock, timeout(1000)).foo(); //succeeds immediatelyMockitoclass- Parameters:
millis- - duration in milliseconds- Returns:
- object that allows fluent specification of the verification
-
validateMockitoUsage
public static void validateMockitoUsage()First of all, in case of any trouble, I encourage you to read the Mockito FAQ: https://github.com/mockito/mockito/wiki/FAQIn case of questions you may also post to mockito mailing list: https://groups.google.com/group/mockito
validateMockitoUsage()explicitly validates the framework state to detect invalid use of Mockito. However, this feature is optional because Mockito validates the usage all the time... but there is a gotcha so read on.Examples of incorrect use:
Mockito throws exceptions if you misuse it so that you know if your tests are written correctly. The gotcha is that Mockito does the validation next time you use the framework (e.g. next time you verify, stub, call mock etc.). But even though the exception might be thrown in the next test, the exception message contains a navigable stack trace element with location of the defect. Hence you can click and find the place where Mockito was misused.//Oops, thenReturn() part is missing: when(mock.get()); //Oops, verified method call is inside verify() where it should be on the outside: verify(mock.execute()); //Oops, missing method to verify: verify(mock);Sometimes though, you might want to validate the framework usage explicitly. For example, one of the users wanted to put
validateMockitoUsage()in his@Aftermethod so that he knows immediately when he misused Mockito. Without it, he would have known about it not sooner than next time he used the framework. One more benefit of havingvalidateMockitoUsage()in@Afteris that jUnit runner and rule will always fail in the test method with defect whereas ordinary 'next-time' validation might fail the next test method. But even though JUnit might report next test as red, don't worry about it and just click at navigable stack trace element in the exception message to instantly locate the place where you misused mockito.Both built-in runner:
MockitoJUnitRunnerand rule:MockitoRuledo validateMockitoUsage() after each test method.Bear in mind that usually you don't have to
validateMockitoUsage()and framework validation triggered on next-time basis should be just enough, mainly because of enhanced exception message with clickable location of defect. However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure (like your own runner or base class for all tests) because adding a special action to@Afterhas zero cost.See examples in javadoc for
Mockitoclass -
withSettings
Allows mock creation with additional mock settings.Don't use it too often. Consider writing simple tests that use simple mocks. Repeat after me: simple tests push simple, KISSy, readable and maintainable code. If you cannot write a test in a simple way - refactor the code under test.
Examples of mock settings:
//Creates mock with different default answer and 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));MockSettingshas been introduced for two reasons. Firstly, to make it easy to add another mock settings when the demand comes. Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods.See javadoc for
MockSettingsto learn about possible mock settings.- Returns:
- mock settings instance with defaults.
-
description
Adds a description to be printed if verification fails.verify(mock, description("This will print on failure")).someMethod("some arg");- Parameters:
description- The description to print on failure.- Returns:
- verification mode
- Since:
- 2.1.0
-
framework
For advanced users or framework integrators. SeeMockitoFrameworkclass.- Since:
- 2.1.0
-
mockitoSession
MockitoSessionis an optional, highly recommended feature that drives writing cleaner tests by eliminating boilerplate code and adding extra validation.For more information, including use cases and sample code, see the javadoc for
MockitoSession.- Since:
- 2.7.0
-
lenient
Lenient stubs bypass "strict stubbing" validation (seeStrictness.STRICT_STUBS). When stubbing is declared as lenient, it will not be checked for potential stubbing problems such as 'unnecessary stubbing' (UnnecessaryStubbingException) or for 'stubbing argument mismatch'PotentialStubbingProblem.
Most mocks in most tests don't need leniency and should happily prosper withlenient().when(mock.foo()).thenReturn("ok");Strictness.STRICT_STUBS.- If a specific stubbing needs to be lenient - use this method
- If a specific mock need to have lenient stubbings - use
MockSettings.strictness(Strictness) - If a specific test method / test class needs to have all stubbings lenient
- configure strictness using our JUnit support (
MockitoJUnitor Mockito Session (MockitoSession)
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.This example is simplified and not realistic. Pushing stubbings to 'before()' method may cause tests to be less readable. Some repetition in tests is OK, use your own judgement to write great tests! It is not desired to eliminate all possible duplication from the test code because it may add complexity and conceal important test information.
public class SomeTest { @Rule public MockitoRule mockito = MockitoJUnit.rule().strictness(STRICT_STUBS); @Mock Foo foo; @Mock Bar bar; @Before public void before() { when(foo.foo()).thenReturn("ok"); // it is better to configure the stubbing to be lenient: // lenient().when(foo.foo()).thenReturn("ok"); // or the entire mock to be lenient: // foo = mock(Foo.class, withSettings().lenient()); } @Test public void test1() { foo.foo(); } @Test public void test2() { foo.foo(); } @Test public void test3() { bar.bar(); } }- Since:
- 2.20.0
-