Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito;
import org.mockito.exceptions.misusing.PotentialStubbingProblem;
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
import org.mockito.internal.MockitoCore;
import org.mockito.internal.creation.MockSettingsImpl;
import org.mockito.internal.framework.DefaultMockitoFramework;
import org.mockito.internal.session.DefaultMockitoSessionBuilder;
import org.mockito.internal.util.MockUtil;
import org.mockito.internal.verification.VerificationModeFactory;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.InvocationFactory;
import org.mockito.invocation.MockHandler;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoJUnitRunner.Strict;
import org.mockito.junit.MockitoRule;
import org.mockito.listeners.VerificationStartedEvent;
import org.mockito.listeners.VerificationStartedListener;
import org.mockito.mock.SerializableMode;
import org.mockito.plugins.MockMaker;
import org.mockito.plugins.MockitoPlugins;
import org.mockito.quality.MockitoHint;
import org.mockito.quality.Strictness;
import org.mockito.session.MockitoSessionBuilder;
import org.mockito.session.MockitoSessionLogger;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.Answer1;
import org.mockito.stubbing.LenientStubber;
import org.mockito.stubbing.OngoingStubbing;
import org.mockito.stubbing.Stubber;
import org.mockito.stubbing.VoidAnswer1;
import org.mockito.verification.After;
import org.mockito.verification.Timeout;
import org.mockito.verification.VerificationAfterDelay;
import org.mockito.verification.VerificationMode;
import org.mockito.verification.VerificationWithTimeout;
import java.util.function.Consumer;
import java.util.function.Function;
/**
*
* The Mockito library enables mock creation, verification and stubbing.
*
*
* 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.
*
*
*
* 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!
*
*
*
* 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:
*
*
*
* 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.
*
*
*
* 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:
*
*
*
* The following examples mock a List, because most people are familiar with the interface (such as the
* add(), get(), clear() methods).
* In reality, please don't mock the List class. Use a real instance instead.
*
*
* //You can mock concrete classes, not just interfaces
* LinkedList mockedList = mock(LinkedList.class);
*
* //stubbing
* when(mockedList.get(0)).thenReturn("first");
* when(mockedList.get(1)).thenThrow(new RuntimeException());
*
* //following prints "first"
* System.out.println(mockedList.get(0));
*
* //following throws runtime exception
* System.out.println(mockedList.get(1));
*
* //following prints "null" because get(999) was not stubbed
* System.out.println(mockedList.get(999));
*
* //Although it is possible to verify a stubbed invocation, usually it's just redundant
* //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
* //If your code doesn't care what get(0) returns, then it should not be stubbed.
* verify(mockedList).get(0);
*
*
*
*
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 overriding 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.
*
* 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 built-in anyInt() argument matcher
* when(mockedList.get(anyInt())).thenReturn("element");
*
* //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):
* when(mockedList.contains(argThat(isValid()))).thenReturn(true);
*
* //following prints "element"
* System.out.println(mockedList.get(999));
*
* //you can also verify using an argument matcher
* verify(mockedList).get(anyInt());
*
* //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.
* {@link ArgumentMatchers Click here} {@link org.mockito.hamcrest.MockitoHamcrest 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 {@link ArgumentMatcher} class.
*
* Be reasonable with using complicated argument matching.
* The natural matching style using equals() with occasional anyX() matchers tend to give clean and 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.
*
* Also, read section 15 or javadoc for {@link ArgumentCaptor} class.
* {@link ArgumentCaptor} is a special implementation of an argument matcher that captures argument values for further assertions.
*
* Warning on argument matchers:
*
* 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:
*
*
* verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
* //above is correct - eq() is also an argument matcher
*
* verify(mock).someMethod(anyInt(), anyString(), "third argument");
* //above is incorrect - exception will be thrown because third argument is given without an argument matcher.
*
*
*
* Matcher methods like any(), 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 any(), eq() methods outside of verified/stubbed method.
*
*
*
*
*
* // A. Single mock whose methods must be invoked in a particular order
* List singleMock = mock(List.class);
*
* //using a single mock
* singleMock.add("was added first");
* singleMock.add("was added second");
*
* //create an inOrder verifier for a single mock
* InOrder inOrder = inOrder(singleMock);
*
* //following will make sure that add is first called with "was added first", then with "was added second"
* inOrder.verify(singleMock).add("was added first");
* inOrder.verify(singleMock).add("was added second");
*
* // B. Multiple mocks that must be used in a particular order
* List firstMock = mock(List.class);
* List secondMock = mock(List.class);
*
* //using mocks
* firstMock.add("was called first");
* secondMock.add("was called second");
*
* //create inOrder object passing any mocks that need to be verified in order
* 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");
*
* // Oh, and A + B can be mixed together at will
*
*
* 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.
*
*
*
*
*
* //using mocks - only mockOne is interacted
* mockOne.add("one");
*
* //ordinary verification
* verify(mockOne).add("one");
*
* //verify that method was never called on a mock
* verify(mockOne, never()).add("two");
*
*
*
* 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 {@link Mockito#never()} - it is more explicit and
* communicates the intent well.
*
*
* Important! This needs to be somewhere in the base class or a test
* runner:
*
*
* MockitoAnnotations.openMocks(testClass);
*
*
* You can use built-in runner: {@link MockitoJUnitRunner} or a rule: {@link MockitoRule}.
* For JUnit5 tests, refer to the JUnit5 extension described in section 45.
*
*
* Sometimes we need to stub with different return value/exception for the same
* method call. Typical use case could be mocking iterators.
* Original version of Mockito did not have this feature to promote simple mocking.
* For example, instead of iterators one could use {@link Iterable} or simply
* collections. Those offer natural ways of stubbing (e.g. using real
* collections). In rare scenarios stubbing consecutive calls could be useful,
* though:
*
*
* Warning : if instead of chaining {@code .thenReturn()} calls, multiple stubbing with the same matchers or arguments
* is used, then each stubbing will override the previous one:
*
*
*
* Allows stubbing with generic {@link Answer} interface.
*
* 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 and 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(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Object mock = invocation.getMock();
* return "called with arguments: " + Arrays.toString(args);
* }
* });
*
* //Following prints "called with arguments: [foo]"
* System.out.println(mock.someMethod("foo"));
*
*
* Stubbing void methods requires a different approach from {@link Mockito#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:
*
* You can use doThrow(), doAnswer(), doNothing(), doReturn()
* and doCallRealMethod() in place of the corresponding call with when(), for any method.
* It is necessary when you
*
*
stub void methods
*
stub methods on spy objects (see below)
*
stub the same method more than once, to change the behaviour of a mock in the middle of a test.
*
* but you may prefer to use these methods in place of the alternative with when(), for all of your stubbing calls.
*
*
* You can create spies of real objects. When you use the spy then the real methods are called
* (unless a method was stubbed).
*
* 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).
*
*
*
* 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 {@link Mockito#when(Object)} for stubbing spies.
* Therefore when using spies please consider doReturn|Answer|Throw() family 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.
*
*
* You can create a mock with specified strategy for its return values.
* It's quite an advanced feature and typically you don't need it to write decent tests.
* However, it can be helpful for working with legacy systems.
*
* It is the default answer so it will be used only when you don't stub the method call.
*
*
*
* Mockito verifies argument values in natural java style: by using an equals() method.
* This is also the recommended way of matching arguments because it makes tests clean and simple.
* In some situations though, it is helpful to assert on certain arguments after the actual verification.
* For example:
*
*
* 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.
*
* In a way ArgumentCaptor is related to custom argument matchers (see javadoc for {@link ArgumentMatcher} class).
* Both techniques can be used for making sure certain arguments were passed to mocks.
* However, ArgumentCaptor may be a better fit if:
*
*
custom argument matcher is not likely to be reused
*
you just need it to assert on argument values to complete verification
*
* Custom argument matchers via {@link ArgumentMatcher} are usually better for stubbing.
*
*
*
*
*
*
* Finally, after many internal debates and discussions on the mailing list, partial mock support was added to Mockito.
* Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.
*
* Before release 1.8spy() was not producing real partial mocks and it was confusing for some users.
* Read more about spying: here or in javadoc for {@link Mockito#spy(Object)} method.
*
*
* //you can create partial mock with spy() method:
* List list = spy(new LinkedList());
*
* //you can enable partial mock capabilities selectively on mocks:
* Foo mock = mock(Foo.class);
* //Be sure the real implementation is 'safe'.
* //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.
* when(mock.someMethod()).thenCallRealMethod();
*
*
* 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 and well-designed code.
*
*
*
*
*
*
* Using this method could be an indication of poor testing.
* 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 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 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 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
*
* 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 {@link Mockito#validateMockitoUsage()}
*
*
*
*
*
*
* Behavior Driven Development style of writing tests uses //given //when //then comments as fundamental parts of your test methods.
* This is exactly how we write our tests and we warmly encourage you to do so!
*
* 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 {@link BDDMockito} class introduces an alias so that you stub method calls with {@link BDDMockito#given(Object)} method.
* Now it really nicely integrates with the given component of a BDD style test!
*
*
* Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
*
* WARNING: This should be rarely used in unit testing.
*
* The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This
* was in a web environment and the objects from the external dependency were being serialized to pass between layers.
*
* To create serializable mock use {@link MockSettings#serializable()}:
*
* List serializableMock = mock(List.class, withSettings().serializable());
*
* 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.
*
*
* List<Object> list = new ArrayList<Object>();
* List<Object> spy = mock(ArrayList.class, withSettings()
* .spiedInstance(list)
* .defaultAnswer(CALLS_REAL_METHODS)
* .serializable());
*
* Release 1.8.3 brings new annotations that may be helpful on occasion:
*
*
*
@{@link Captor} simplifies creation of {@link ArgumentCaptor}
* - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings
*
@{@link Spy} - you can use it instead {@link Mockito#spy(Object)}.
*
@{@link InjectMocks} - injects mock or spy fields into tested object automatically.
*
*
*
* Note that @{@link InjectMocks} can also be used in combination with the @{@link 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.
*
*
* All new annotations are *only* processed on {@link MockitoAnnotations#openMocks(Object)}.
* Just like for @{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner} or rule:
* {@link MockitoRule}.
*
* 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.
*
* Not yet implemented to work with InOrder verification.
*
* Examples:
*
*
* //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();
*
* Mockito will now try to instantiate @{@link Spy} and will instantiate @{@link InjectMocks} fields
* using constructor injection, setter injection, or field injection.
*
* To take advantage of this feature you need to use {@link MockitoAnnotations#openMocks(Object)}, {@link MockitoJUnitRunner}
* or {@link MockitoRule}.
*
* Read more about available tricks and the rules of injection in the javadoc for {@link InjectMocks}
*
* //instead:
* @Spy BeerDrinker drinker = new BeerDrinker();
* //you can write:
* @Spy BeerDrinker drinker;
*
* //same applies to @InjectMocks annotation:
* @InjectMocks LocalPub;
*
* 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 and stubbed at field initialization in a test:
*
* public class CarTest {
* Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();
*
* @Test public void should... {}
*
* 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.
*
* Warning, ignoreStubs() might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...));
* Bear in mind that Mockito does not recommend bombarding every test with verifyNoMoreInteractions()
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(Object...)}
*
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:
*
*
Final classes but with an interface
*
Already custom proxied object
*
Special objects with a finalize method, i.e. to avoid executing it 2 times
*
*
*
The difference with the regular spy:
*
*
* The regular spy ({@link #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.
*
*
*
*
* See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}.
*
*
*
*
*
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 {@link org.mockito.plugins.MockMaker}.
*
*
*
*
*
*
* It is now possible to conveniently spy on abstract classes. Note that overusing spies hints at code design smells (see {@link #spy(Object)}).
*
* 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.
*
*
* //convenience API, new overloaded spy() method:
* SomeAbstract spy = spy(SomeAbstract.class);
*
* //Mocking abstract methods, spying default methods of an interface (only available since 2.7.13)
* Function<Foo, Bar> function = spy(Function.class);
*
* //Robust API, via settings builder:
* OtherAbstract spy = mock(OtherAbstract.class, withSettings()
* .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking an abstract class with constructor arguments (only available since 2.7.14)
* SomeAbstract spy = mock(SomeAbstract.class, withSettings()
* .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS));
*
* //Mocking a non-static inner abstract class:
* InnerAbstract spy = mock(InnerAbstract.class, withSettings()
* .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));
*
*
* For more information please see {@link MockSettings#useConstructor(Object...)}.
*
*
*
*
*
*
* Mockito introduces serialization across classloader.
*
* Like with any other form of serialization, all types in the mock hierarchy have to serializable, including answers.
* As this serialization mode require considerably more work, this is an opt-in setting.
*
*
* // use regular serialization
* mock(Book.class, withSettings().serializable());
*
* // use serialization across classloaders
* mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS));
*
*
* For more details see {@link MockSettings#serializable(SerializableMode)}.
*
*
*
*
*
*
* Deep stubbing has been improved to find generic information if available in the class.
* That means that classes like this can be used without having to mock the behavior.
*
*
* class Lines extends List<Line> {
* // ...
* }
*
* lines = mock(Lines.class, RETURNS_DEEP_STUBS);
*
* // Now Mockito understand this is not an Object but a Line
* Line line = lines.iterator().next();
*
*
* Please note that in most scenarios a mock returning a mock is wrong.
*
*
*
*
*
*
* Mockito now offers a JUnit rule. Until now in JUnit there were two ways to initialize fields annotated by Mockito annotations
* such as @{@link Mock}, @{@link Spy}, @{@link InjectMocks}, etc.
*
*
*
Annotating the JUnit test class with a @{@link org.junit.runner.RunWith}({@link MockitoJUnitRunner}.class)
*
Invoking {@link MockitoAnnotations#openMocks(Object)} in the @{@link org.junit.Before} method
*
*
* Now you can choose to use a rule :
*
*
* @RunWith(YetAnotherRunner.class)
* public class TheTest {
* @Rule public MockitoRule mockito = MockitoJUnit.rule();
* // ...
* }
*
*
* For more information see {@link MockitoJUnit#rule()}.
*
*
*
*
*
*
* An incubating feature made it's way in mockito that will allow to toggle a mockito-plugin.
*
* More information here {@link org.mockito.plugins.PluginSwitch}.
*
*
*
* Allows specifying a custom message to be printed if verification fails.
*
* Examples:
*
*
*
* // will print a custom message on verification failure
* verify(mock, description("This will print on failure")).someMethod();
*
* // will work with any verification mode
* verify(mock, times(2).description("someMethod should be called twice")).someMethod();
*
* You can use Java 8 lambda expressions with {@link ArgumentMatcher} to reduce the dependency on {@link ArgumentCaptor}.
* If you need to verify that the input to a function call on a mock was correct, then you would normally
* use the {@link 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:
*
*
*
* // verify a list only had strings of a certain length added to it
* // note - this will only compile under Java 8
* verify(list, times(2)).add(argThat(string -> string.length() < 5));
*
* // Java 7 equivalent - not as neat
* verify(list, times(2)).add(argThat(new ArgumentMatcher<String>(){
* public boolean matches(String arg) {
* return arg.length() < 5;
* }
* }));
*
* // more complex Java 8 example - where you can specify complex verification behaviour functionally
* verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubObject().get(0).equals("expected")));
*
* // this can also be used when defining the behaviour of a mock under different inputs
* // in this case if the input list was fewer than 3 items the mock returns null
* when(mock.someMethod(argThat(list -> list.size()<3))).thenReturn(null);
*
* As the {@link 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 {@link org.mockito.invocation.InvocationOnMock}.
*
*
* Examples:
*
*
* // answer by returning 12 every time
* doAnswer(invocation -> 12).when(mock).doSomething();
*
* // answer by using one of the parameters - converting into the right
* // type as your go - in this case, returning the length of the second string parameter
* // as the answer. This gets long-winded quickly, with casting of parameters.
* doAnswer(invocation -> ((String)invocation.getArgument(1)).length())
* .when(mock).doSomething(anyString(), anyString(), anyString());
*
*
* 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 {@link AdditionalAnswers#answer(Answer1)}} and {@link AdditionalAnswers#answerVoid(VoidAnswer1)}
* 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:
*
*
*
* // Example interface to be mocked has a function like:
* void execute(String operand, Callback callback);
*
* // the example callback has a function and the class under test
* // will depend on the callback being invoked
* void receive(String item);
*
* // Java 8 - style 1
* doAnswer(AdditionalAnswers.<String,Callback>answerVoid((operand, callback) -> callback.receive("dummy")))
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 8 - style 2 - assuming static import of AdditionalAnswers
* doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy")))
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 8 - style 3 - where mocking function to is a static member of test class
* private static void dummyCallbackImpl(String operation, Callback callback) {
* callback.receive("dummy");
* }
*
* doAnswer(answerVoid(TestClass::dummyCallbackImpl))
* .when(mock).execute(anyString(), any(Callback.class));
*
* // Java 7
* doAnswer(answerVoid(new VoidAnswer2<String, Callback>() {
* public void answer(String operation, Callback callback) {
* callback.receive("dummy");
* }})).when(mock).execute(anyString(), any(Callback.class));
*
* // returning a value is possible with the answer() function
* // and the non-void version of the functional interfaces
* // so if the mock interface had a method like
* boolean isSameString(String input1, String input2);
*
* // this could be mocked
* // Java 8
* doAnswer(AdditionalAnswers.<Boolean,String,String>answer((input1, input2) -> input1.equals(input2)))
* .when(mock).execute(anyString(), anyString());
*
* // Java 7
* doAnswer(answer(new Answer2<String, String, String>() {
* public String 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:
*
*
*
* Mockito now offers support for mocking final classes and methods by default.
* 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.
* Since 5.0.0, this feature is enabled by default.
*
*
* 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.
*
*
* In versions preceding 5.0.0, this mock maker is turned off by default because it is based on
* completely different mocking mechanism that required 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.
*
*
* Some noteworthy notes about this mock maker:
*
*
Mocking final types and enums is incompatible with mock settings like :
*
*
explicitly serialization support withSettings().serializable()
*
extra-interfaces withSettings().extraInterfaces()
*
*
*
Some methods cannot be mocked
*
*
Package-visible methods of java.*
*
native methods
*
*
*
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
*
*
Strict stubbing if you cannot use runner/rule - {@link MockitoSession}
*
Unnecessary stubbing detection with {@link MockitoJUnitRunner}
*
Stubbing argument mismatch warnings, documented in {@link MockitoHint}
*
*
* 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.
*
*
*
* In Summer 2017 we decided that Mockito
*
* should offer better API
*
* for advanced framework integrations.
* The new API is not intended for users who want to write unit tests.
* It is intended for other test tools and mocking frameworks that need to extend or wrap Mockito with some custom logic.
* During the design and implementation process (issue 1110)
* we have developed and changed following public API elements:
*
*
New {@link MockitoPlugins} -
* Enables framework integrators to get access to default Mockito plugins.
* Useful when one needs to implement custom plugin such as {@link MockMaker}
* and delegate some behavior to the default Mockito implementation.
*
*
New {@link MockSettings#build(Class)} -
* Creates immutable view of mock settings used later by Mockito.
* Useful for creating invocations with {@link InvocationFactory} or when implementing custom {@link MockHandler}.
*
*
New {@link MockingDetails#getMockHandler()} -
* Other frameworks may use the mock handler to programmatically simulate invocations on mock objects.
*
*
New {@link MockHandler#getMockSettings()} -
* Useful to get hold of the setting the mock object was created with.
*
*
New {@link InvocationFactory} -
* Provides means to create instances of {@link Invocation} objects.
* Useful for framework integrations that need to programmatically simulate method calls on mock objects.
*
*
New {@link MockHandler#getInvocationContainer()} -
* Provides access to invocation container object which has no methods (marker interface).
* Container is needed to hide the internal implementation and avoid leaking it to the public API.
*
*
Changed {@link org.mockito.stubbing.Stubbing} -
* it now extends {@link Answer} interface.
* It is backwards compatible because Stubbing interface is not extensible (see {@link NotExtensible}).
* The change should be seamless to our users.
*
*
{@link NotExtensible} -
* Public annotation that indicates to the user that she should not provide custom implementations of given type.
* Helps framework integrators and our users understand how to use Mockito API safely.
*
*
* Do you have feedback? Please leave comment in issue 1110.
*
*
*
* Framework integrations such as Spring Boot needs public API to tackle double-proxy use case
* (issue 1191).
* We added:
*
*
New {@link VerificationStartedListener} and {@link VerificationStartedEvent}
* enable framework integrators to replace the mock object for verification.
* The main driving use case is Spring Boot integration.
* For details see Javadoc for {@link VerificationStartedListener}.
*
*
New public method {@link MockSettings#verificationStartedListeners(VerificationStartedListener...)}
* allows to supply verification started listeners at mock creation time.
*
*
New handy method {@link MockingDetails#getMock()} was added to make the {@code MockingDetails} API more complete.
* We found this method useful during the implementation.
*
{@link MockitoSessionBuilder} and {@link MockitoSession} were enhanced to enable reuse by testing framework
* integrations (e.g. {@link MockitoRule} for JUnit):
*
*
{@link MockitoSessionBuilder#initMocks(Object...)} allows to pass in multiple test class instances for
* initialization of fields annotated with Mockito annotations like {@link org.mockito.Mock}.
* This method is useful for advanced framework integrations (e.g. JUnit Jupiter), when a test uses multiple,
* e.g. nested, test class instances.
*
*
{@link MockitoSessionBuilder#name(String)} allows to pass a name from the testing framework to the
* {@link MockitoSession} that will be used for printing warnings when {@link Strictness#WARN} is used.
*
*
{@link MockitoSessionBuilder#logger(MockitoSessionLogger)} makes it possible to customize the logger used
* for hints/warnings produced when finishing mocking (useful for testing and to connect reporting capabilities
* provided by testing frameworks such as JUnit Jupiter).
*
*
{@link MockitoSession#setStrictness(Strictness)} allows to change the strictness of a {@link MockitoSession}
* for one-off scenarios, e.g. it enables configuring a default strictness for all tests in a class but makes it
* possible to change the strictness for a single or a few tests.
*
*
{@link MockitoSession#finishMocking(Throwable)} was added to avoid confusion that may arise because
* there are multiple competing failures. It will disable certain checks when the supplied failure
* is not {@code null}.
*
org.mockito.plugins.InstantiatorProvider returned an internal API. Hence it was deprecated and replaced
* by {@link org.mockito.plugins.InstantiatorProvider2}. org.mockito.plugins.InstantiatorProvider
* has now been removed.
*
* For integration with JUnit Jupiter (JUnit5+), use the `org.mockito:mockito-junit-jupiter` artifact.
* For more information about the usage of the integration, see the JavaDoc of MockitoExtension.
*
*
*
* Strict stubbing feature is available since early Mockito 2.
* It is very useful because it drives cleaner tests and improved productivity.
* Strict stubbing reports unnecessary stubs, detects stubbing argument mismatch and makes the tests more DRY ({@link Strictness#STRICT_STUBS}).
* This comes with a trade-off: in some cases, you may get false negatives from strict stubbing.
* To remedy those scenarios you can now configure specific stubbing to be lenient, while all the other stubbings and mocks use strict stubbing:
*
*
* 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:
*
*
*
* In certain specific, rare scenarios (issue #1619)
* inline mocking causes memory leaks.
* There is no clean way to mitigate this problem completely.
* Hence, we introduced a new API to explicitly clear mock state (only make sense in inline mocking!).
* See example usage in {@link MockitoFramework#clearInlineMocks()}.
* If you have feedback or a better idea how to solve the problem please reach out.
*
*
*
*
* When using the inline mock maker, it is possible to mock static method invocations within the current
* thread and a user-defined scope. This way, Mockito assures that concurrently and sequentially running tests do not interfere.
*
* To make sure a static mock remains temporary, it is recommended to define the scope within a try-with-resources construct.
* In the following example, the Foo type's static method would return foo unless mocked:
*
*
*
* Due to the defined scope of the static mock, it returns to its original behavior once the scope is released. To define mock
* behavior and to verify static method invocations, use the MockedStatic that is returned.
*
*
* When using the inline mock maker, it is possible to generate mocks on constructor invocations within the current
* thread and a user-defined scope. This way, Mockito assures that concurrently and sequentially running tests do not interfere.
*
* To make sure a constructor mocks remain temporary, it is recommended to define the scope within a try-with-resources construct.
* In the following example, the Foo type's construction would generate a mock:
*
*
*
* Due to the defined scope of the mocked construction, object construction returns to its original behavior once the scope is
* released. To define mock behavior and to verify method invocations, use the MockedConstruction that is returned.
*
*
* The JVM offers the {@link java.lang.reflect.Proxy} facility for creating dynamic proxies of interface types. For most applications, Mockito
* must be capable of mocking classes as supported by the default mock maker, or even final classes, as supported by the inline mock maker. To
* create such mocks, Mockito requires to setup diverse JVM facilities and must apply code generation. If only interfaces are supposed to be
* mocked, one can however choose to use a org.mockito.internal.creation.proxy.ProxyMockMaker that is based on the {@link java.lang.reflect.Proxy}
* API which avoids diverse overhead of the other mock makers but also limits mocking to interfaces.
*
* This mock maker 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-proxy.
*
*
*
* In some cases, mocking a class/interface can lead to unexpected runtime behavior. For example, mocking a java.util.List
* is difficult, given the requirements imposed by the interface. This means that on runtime, depending on what methods the application
* calls on the list, your mock might behave in such a way that it violates the interface.
*
*
* For any class/interface you own that is problematic to mock, you can now mark the class with {@link org.mockito.DoNotMock @DoNotMock}. For usage
* of the annotation and how to ship your own (to avoid a compile time dependency on a test artifact), please see its JavaDoc.
*
*
* You can now customize the strictness level for a single mock, either using `@Mock` annotation strictness attribute or
* using `MockSettings.strictness()`. This can be useful if you want all of your mocks to be strict,
* but one of the mocks to be lenient.
*
*
*
* You may encounter situations where you want to use a different mock maker for a specific test only.
* In such case, you can (temporarily) use {@link MockSettings#mockMaker(String)} and {@link Mock#mockMaker()}
* to specify the mock maker for a specific mock which is causing the problem.
*
*
*
* Instead of calling method {@link Mockito#mock(Class)} or {@link Mockito#spy(Class)} with Class parameter, you can
* now call method {@code mock()} or {@code spy()} without parameters:
*
*
* Foo foo = Mockito.mock();
* Bar bar = Mockito.spy();
*
*
* Mockito will automatically detect the needed class.
*
* It works only if you assign result of {@code mock()} or {@code spy()} to a variable or field with an explicit type.
* With an implicit type, the Java compiler is unable to automatically determine the type of a mock and you need
* to pass in the {@code Class} explicitly.
*
*
* To validate arguments during verification, instead of capturing them with {@link ArgumentCaptor}, you can now
* use {@link ArgumentMatchers#assertArg(Consumer)}}:
*
*
*/
@CheckReturnValue
@SuppressWarnings("unchecked")
public class Mockito extends ArgumentMatchers {
static final MockitoCore MOCKITO_CORE = new MockitoCore();
/**
* The default Answer of every mock if the mock was not stubbed.
*
* Typically, it just returns some empty value.
*
* {@link Answer} can 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.
*/
public static final Answer
*
*
* 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();
*
* 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.
*
*/
public static final Answer RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;
/**
* Optional Answer to be used with {@link Mockito#mock(Class, Answer)}
*
*
* {@link Answer} can 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 use doReturn syntax.
*
* Note 2: If the mock is serialized then deserialized, then this answer will not be able to understand
* generics metadata.
*/
public static final Answer CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;
/**
* Optional Answer to be used with {@link Mockito#mock(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 {@code Object}) it will match and return the mock.
*
* Consider a HttpBuilder used in a HttpRequesterWithHeaders.
*
*
*/
public static final Answer RETURNS_SELF = Answers.RETURNS_SELF;
/**
* Creates a mock object of the requested class or interface.
*
* See examples in javadoc for the {@link Mockito} class.
*
* @param reified don't pass any values to it. It's a trick to detect the class/interface you
* want to mock.
* @return the mock object.
* @since 4.9.0
*/
@SafeVarargs
public static T mock(T... reified) {
return mock(withSettings(), reified);
}
/**
* Creates a mock object of the requested class or interface with the given default answer.
*
* See examples in javadoc for the {@link Mockito} class.
*
* @param defaultAnswer the default answer to use.
* @param reified don't pass any values to it. It's a trick to detect the class/interface you
* want to mock.
* @return the mock object.
*/
@SafeVarargs
public static T mock(@SuppressWarnings("rawtypes") Answer defaultAnswer, T... reified) {
return mock(withSettings().defaultAnswer(defaultAnswer), reified);
}
/**
* Creates a mock object of the requested class or interface with the given name.
*
* See examples in javadoc for the {@link Mockito} class.
*
* @param name the mock name to use.
* @param reified don't pass any values to it. It's a trick to detect the class/interface you
* want to mock.
* @return the mock object.
*/
@SafeVarargs
public static T mock(String name, T... reified) {
return mock(withSettings().name(name).defaultAnswer(RETURNS_DEFAULTS), reified);
}
/**
* Creates a mock object of the requested class or interface with the given settings.
*
* See examples in javadoc for the {@link Mockito} class.
*
* @param settings the mock settings to use.
* @param reified don't pass any values to it. It's a trick to detect the class/interface you
* want to mock.
* @return the mock object.
*/
@SafeVarargs
public static T mock(MockSettings settings, T... reified) {
if (reified == null || reified.length > 0) {
throw new IllegalArgumentException(
"Please don't pass any values here. Java will detect class automagically.");
}
return mock(getClassOf(reified), settings);
}
/**
* Creates mock object of given class or interface.
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @return mock object
*/
public static T mock(Class classToMock) {
return mock(classToMock, withSettings());
}
/**
* 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. {@link Mock Read more.}
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param name of the mock
* @return mock object
*/
public static T mock(Class classToMock, String name) {
return mock(classToMock, withSettings().name(name).defaultAnswer(RETURNS_DEFAULTS));
}
/**
* 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.
*
* @param toInspect - object to inspect. null input is allowed.
* @return A {@link org.mockito.MockingDetails} instance.
* @since 1.9.5
*/
public static MockingDetails mockingDetails(Object toInspect) {
return MOCKITO_CORE.mockingDetails(toInspect);
}
/**
* 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.
*
*
*
* @param classToMock class or interface to mock
* @param defaultAnswer default answer for un-stubbed methods
*
* @return mock object
*/
public static T mock(Class classToMock, Answer defaultAnswer) {
return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));
}
/**
* 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 {@link 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?
*
* See also {@link Mockito#withSettings()}
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @param mockSettings additional mock settings
* @return mock object
*/
public static T mock(Class classToMock, MockSettings mockSettings) {
return MOCKITO_CORE.mock(classToMock, mockSettings);
}
/**
* 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 {@link Mockito#when(Object)} for stubbing spies.
* Therefore for spies it is recommended to always use doReturn|Answer|Throw()|CallRealMethod
* family 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 {@link Mockito} class
*
*
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.
*
*
* @param object
* to spy on
* @return a spy of the real object
*/
public static T spy(T object) {
if (MockUtil.isMock(object)) {
throw new IllegalArgumentException(
"Please don't pass mock here. Spy is not allowed on mock.");
}
return MOCKITO_CORE.mock(
(Class) object.getClass(),
withSettings().spiedInstance(object).defaultAnswer(CALLS_REAL_METHODS));
}
/**
* Please refer to the documentation of {@link #spy(Object)}.
* Overusing spies hints at code design smells.
*
* This method, in contrast to the original {@link #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 also {@link MockSettings#useConstructor(Object...)}.
*
*
* @param classToSpy the class to spy
* @param type of the spy
* @return a spy of the provided class
* @since 1.10.12
*/
public static T spy(Class classToSpy) {
return MOCKITO_CORE.mock(
classToSpy, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));
}
/**
* Please refer to the documentation of {@link #spy(Class)}.
*
* @param reified don't pass any values to it. It's a trick to detect the class/interface you want to mock.
* @return spy object
* @since 4.9.0
*/
@SafeVarargs
public static T spy(T... reified) {
if (reified.length > 0) {
throw new IllegalArgumentException(
"Please don't pass any values here. Java will detect class automagically.");
}
return spy(getClassOf(reified));
}
private static Class getClassOf(T[] array) {
return (Class) array.getClass().getComponentType();
}
/**
* Creates a thread-local mock controller for all static methods of the given class or interface.
* The returned object's {@link MockedStatic#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 {@link Mockito} class
*
* @param classToMock class or interface of which static mocks should be mocked.
* @return mock controller
*/
public static MockedStatic mockStatic(Class classToMock) {
return mockStatic(classToMock, withSettings());
}
/**
* Creates a thread-local mock controller for all static methods of the given class or interface.
* The returned object's {@link MockedStatic#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 {@link Mockito} class
*
* @param classToMock class or interface of which static mocks should be mocked.
* @param defaultAnswer the default answer when invoking static methods.
* @return mock controller
*/
public static MockedStatic mockStatic(Class classToMock, Answer defaultAnswer) {
return mockStatic(classToMock, withSettings().defaultAnswer(defaultAnswer));
}
/**
* Creates a thread-local mock controller for all static methods of the given class or interface.
* The returned object's {@link MockedStatic#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 {@link Mockito} class
*
* @param classToMock class or interface of which static mocks should be mocked.
* @param name the name of the mock to use in error messages.
* @return mock controller
*/
public static MockedStatic mockStatic(Class classToMock, String name) {
return mockStatic(classToMock, withSettings().name(name));
}
/**
* Creates a thread-local mock controller for all static methods of the given class or interface.
* The returned object's {@link MockedStatic#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 {@link Mockito} class
*
* @param classToMock class or interface of which static mocks should be mocked.
* @param mockSettings the settings to use where only name and default answer are considered.
* @return mock controller
*/
public static MockedStatic mockStatic(Class classToMock, MockSettings mockSettings) {
return MOCKITO_CORE.mockStatic(classToMock, mockSettings);
}
/**
* Creates a thread-local mock controller for all constructions of the given class.
* The returned object's {@link MockedConstruction#close()} method must be called upon completing the
* test or the mock will remain active on the current thread.
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock non-abstract class of which constructions should be mocked.
* @param defaultAnswer the default answer for the first created mock.
* @param additionalAnswers the default answer for all additional mocks. For any access mocks, the
* last answer is used. If this array is empty, the {@code defaultAnswer} is used.
* @return mock controller
*/
public static MockedConstruction mockConstructionWithAnswer(
Class classToMock, Answer defaultAnswer, Answer... additionalAnswers) {
return mockConstruction(
classToMock,
context -> {
if (context.getCount() == 1 || additionalAnswers.length == 0) {
return withSettings().defaultAnswer(defaultAnswer);
} else if (context.getCount() > additionalAnswers.length) {
return withSettings()
.defaultAnswer(additionalAnswers[additionalAnswers.length - 1]);
} else {
return withSettings()
.defaultAnswer(additionalAnswers[context.getCount() - 2]);
}
},
(mock, context) -> {});
}
/**
* Creates a thread-local mock controller for all constructions of the given class.
* The returned object's {@link MockedConstruction#close()} method must be called upon completing the
* test or the mock will remain active on the current thread.
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock non-abstract class of which constructions should be mocked.
* @return mock controller
*/
public static MockedConstruction mockConstruction(Class classToMock) {
return mockConstruction(classToMock, index -> withSettings(), (mock, context) -> {});
}
/**
* Creates a thread-local mock controller for all constructions of the given class.
* The returned object's {@link MockedConstruction#close()} method must be called upon completing the
* test or the mock will remain active on the current thread.
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock non-abstract class of which constructions should be mocked.
* @param mockInitializer a callback to prepare the methods on a mock after its instantiation.
* @return mock controller
*/
public static MockedConstruction mockConstruction(
Class classToMock, MockedConstruction.MockInitializer mockInitializer) {
return mockConstruction(classToMock, withSettings(), mockInitializer);
}
/**
* Creates a thread-local mock controller for all constructions of the given class.
* The returned object's {@link MockedConstruction#close()} method must be called upon completing the
* test or the mock will remain active on the current thread.
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock non-abstract class of which constructions should be mocked.
* @param mockSettings the mock settings to use.
* @return mock controller
*/
public static MockedConstruction mockConstruction(
Class classToMock, MockSettings mockSettings) {
return mockConstruction(classToMock, context -> mockSettings);
}
/**
* Creates a thread-local mock controller for all constructions of the given class.
* The returned object's {@link MockedConstruction#close()} method must be called upon completing the
* test or the mock will remain active on the current thread.
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock non-abstract class of which constructions should be mocked.
* @param mockSettingsFactory the mock settings to use.
* @return mock controller
*/
public static MockedConstruction mockConstruction(
Class classToMock,
Function mockSettingsFactory) {
return mockConstruction(classToMock, mockSettingsFactory, (mock, context) -> {});
}
/**
* Creates a thread-local mock controller for all constructions of the given class.
* The returned object's {@link MockedConstruction#close()} method must be called upon completing the
* test or the mock will remain active on the current thread.
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock non-abstract class of which constructions should be mocked.
* @param mockSettings the settings to use.
* @param mockInitializer a callback to prepare the methods on a mock after its instantiation.
* @return mock controller
*/
public static MockedConstruction mockConstruction(
Class classToMock,
MockSettings mockSettings,
MockedConstruction.MockInitializer mockInitializer) {
return mockConstruction(classToMock, index -> mockSettings, mockInitializer);
}
/**
* Creates a thread-local mock controller for all constructions of the given class.
* The returned object's {@link MockedConstruction#close()} method must be called upon completing the
* test or the mock will remain active on the current thread.
*
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock non-abstract class of which constructions should be mocked.
* @param mockSettingsFactory a function to create settings to use.
* @param mockInitializer a callback to prepare the methods on a mock after its instantiation.
* @return mock controller
*/
public static MockedConstruction mockConstruction(
Class classToMock,
Function mockSettingsFactory,
MockedConstruction.MockInitializer mockInitializer) {
return MOCKITO_CORE.mockConstruction(classToMock, mockSettingsFactory, mockInitializer);
}
/**
* 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:
*
*
* 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();
*
*
*
* For stubbing void methods with throwables see: {@link Mockito#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 what foo.bar() returns then something else breaks(often before even verify() gets executed).
* If your code doesn't care what get(0) returns then it should not be stubbed.
*
*
* See examples in javadoc for {@link Mockito} class
* @param methodCall method to be stubbed
* @return OngoingStubbing object used to stub fluently.
* Do not create a reference to this returned object.
*/
public static OngoingStubbing when(T methodCall) {
return MOCKITO_CORE.when(methodCall);
}
/**
* Verifies certain behavior happened once.
*
* Arguments passed are compared using equals() method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to 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 what foo.bar() returns then something else breaks(often before even verify() gets executed).
* If your code doesn't care what foo.bar() returns then it should not be stubbed.
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param mock to be verified
* @return mock object itself
*/
public static T verify(T mock) {
return MOCKITO_CORE.verify(mock, times(1));
}
/**
* Verifies certain behavior happened at least once / exact number of times / never. E.g:
*
* verify(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());
*
*
* times(1) is the default and can be omitted
*
* Arguments passed are compared using equals() method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
*
*
* @param mock to be verified
* @param mode times(x), atLeastOnce() or never()
*
* @return mock object itself
*/
public static T verify(T mock, VerificationMode mode) {
return MOCKITO_CORE.verify(mock, mode);
}
/**
* 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 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 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
*
*
* @param The Type of the mocks
* @param mocks to be reset
*/
public static void reset(T... mocks) {
MOCKITO_CORE.reset(mocks);
}
/**
* 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.
*/
public static void clearAllCaches() {
MOCKITO_CORE.clearAllCaches();
}
/**
* 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.
*
*
* Try to avoid this method at all costs. Only clear invocations if you are unable to efficiently test your program.
* @param The type of the mocks
* @param mocks The mocks to clear the invocations for
*/
public static void clearInvocations(T... mocks) {
MOCKITO_CORE.clearInvocations(mocks);
}
/**
* 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 {@link Mockito#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 {@link Strictness#STRICT_STUBS} feature
* introduced in Mockito 2.3.0.
* If you want to ignore stubs for verification, see {@link #ignoreStubs(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(), @Before method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
*
*
* Example:
*
*
* //interactions
* mock.doSomething();
* mock.doSomethingUnexpected();
*
* //verification
* verify(mock).doSomething();
*
* //following will fail because 'doSomethingUnexpected()' is unexpected
* verifyNoMoreInteractions(mock);
*
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
*/
public static void verifyNoMoreInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
* Verifies that no interactions happened on given mocks.
*
* verifyNoInteractions(mockOne, mockTwo);
*
* This method will also detect invocations
* that occurred before the test method, for example: in setUp(), @Before method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
*
* See also {@link Mockito#never()} - it is more explicit and communicates the intent well.
*
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified
* @since 3.0.1
*/
public static void verifyNoInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoInteractions(mocks);
}
/**
* Use doThrow() when you want to stub the void method with an exception.
*
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
*
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doThrow(Throwable... toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
/**
* Use doThrow() 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 {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
*
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
public static Stubber doThrow(Class extends Throwable> toBeThrown) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
/**
* Same as {@link #doThrow(Class)} but sets consecutive exception classes to be thrown. Remember to use
* doThrow() 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 {@link Mockito#when(Object)} because the compiler
* does not like void methods inside brackets...
*
*
* @param toBeThrown to be thrown when the stubbed method is called
* @param toBeThrownNext next to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
// Additional method helps users of JDK7+ to hide heap pollution / unchecked generics array
// creation
@SuppressWarnings({"unchecked", "varargs"})
public static Stubber doThrow(
Class extends Throwable> toBeThrown, Class extends Throwable>... toBeThrownNext) {
return MOCKITO_CORE.stubber().doThrow(toBeThrown, toBeThrownNext);
}
/**
* Use doCallRealMethod() 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 {@link Mockito#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 {@link Mockito} class
*
* @return stubber - to select a method for stubbing
* @since 1.9.5
*/
public static Stubber doCallRealMethod() {
return MOCKITO_CORE.stubber().doCallRealMethod();
}
/**
* Use doAnswer() when you want to stub a void method with generic {@link Answer}.
*
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets...
*
* See examples in javadoc for {@link Mockito} class
*
* @param answer to answer when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doAnswer(Answer answer) {
return MOCKITO_CORE.stubber().doAnswer(answer);
}
/**
* Use doNothing() 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 {@link Mockito} class
*
* @return stubber - to select a method for stubbing
*/
public static Stubber doNothing() {
return MOCKITO_CORE.stubber().doNothing();
}
/**
* Use doReturn() in those rare occasions when you cannot use {@link Mockito#when(Object)}.
*
* Beware that {@link Mockito#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();
*
*
*
*
* Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overriding stubbing is a potential code smell that points out too much stubbing.
*
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @return stubber - to select a method for stubbing
*/
public static Stubber doReturn(Object toBeReturned) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned);
}
/**
* Same as {@link #doReturn(Object)} but sets consecutive values to be returned. Remember to use
* doReturn() in those rare occasions when you cannot use {@link Mockito#when(Object)}.
*
* Beware that {@link Mockito#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();
*
*
*
*
* Above scenarios shows a trade-off of Mockito's elegant syntax. Note that the scenarios are very rare, though.
* Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general
* overriding stubbing is a potential code smell that points out too much stubbing.
*
* See examples in javadoc for {@link Mockito} class
*
* @param toBeReturned to be returned when the stubbed method is called
* @param toBeReturnedNext to be returned in consecutive calls when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 2.1.0
*/
@SuppressWarnings({"unchecked", "varargs"})
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext) {
return MOCKITO_CORE.stubber().doReturn(toBeReturned, toBeReturnedNext);
}
/**
* Creates {@link org.mockito.InOrder} object that allows verifying mocks in order.
*
*
* InOrder inOrder = inOrder(firstMock, 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 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.
*
* As of Mockito 1.8.4 you can verifyNoMoreInteractions() in order-sensitive way. Read more: {@link InOrder#verifyNoMoreInteractions()}
*
* See examples in javadoc for {@link Mockito} class
*
* @param mocks to be verified in order
*
* @return InOrder object to be used to verify in order
*/
public static InOrder inOrder(Object... mocks) {
return MOCKITO_CORE.inOrder(mocks);
}
/**
* Ignores stubbed methods of given mocks for the sake of verification.
* Please consider using {@link Strictness#STRICT_STUBS} feature which eliminates the need for ignoreStubs()
* and provides other benefits.
*
* ignoreStubs() is sometimes useful when coupled with verifyNoMoreInteractions() or verification inOrder().
* Helps to avoid redundant verification of stubbed calls - typically we're not interested in verifying stubs.
*
* Warning, ignoreStubs() might lead to overuse of verifyNoMoreInteractions(ignoreStubs(...));
* Bear in mind that Mockito does not recommend bombarding every test with verifyNoMoreInteractions()
* for the reasons outlined in javadoc for {@link Mockito#verifyNoMoreInteractions(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 {@link org.mockito.InOrder#verifyNoMoreInteractions()}.
* See the second example.
*
* Example:
*
* //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.
*
* Ignoring stubs can be used with verification in order:
*
* List 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();
*
* Stubbed invocations are automatically verified with {@link Strictness#STRICT_STUBS} feature
* and it eliminates the need for ignoreStubs(). 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()
*
*
* @since 1.9.0
* @param mocks input mocks that will be changed
* @return the same mocks that were passed in as parameters
*/
public static Object[] ignoreStubs(Object... mocks) {
return MOCKITO_CORE.ignoreStubs(mocks);
}
/**
* Allows verifying exact number of invocations. E.g:
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param wantedNumberOfInvocations wanted number of invocations
*
* @return verification mode
*/
public static VerificationMode times(int wantedNumberOfInvocations) {
return VerificationModeFactory.times(wantedNumberOfInvocations);
}
/**
* Alias to times(0), see {@link Mockito#times(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 {@link Mockito#verifyNoMoreInteractions(Object...)}
*
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode never() {
return times(0);
}
/**
* Allows at-least-once verification. E.g:
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param maxNumberOfInvocations max number of invocations
*
* @return verification mode
*/
public static VerificationMode atMost(int maxNumberOfInvocations) {
return VerificationModeFactory.atMost(maxNumberOfInvocations);
}
/**
* Allows non-greedy verification in order. For example
*
will not fail if the method is called 3 times, unlike times( 2 )
*
will not mark the third invocation as verified, unlike atLeast( 2 )
*
* This verification mode can only be used with in order verification.
* @param wantedNumberOfInvocations number of invocations to verify
* @return verification mode
*/
public static VerificationMode calls(int wantedNumberOfInvocations) {
return VerificationModeFactory.calls(wantedNumberOfInvocations);
}
/**
* 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 {@link Mockito#verifyNoMoreInteractions(Object...)}
*
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode only() {
return VerificationModeFactory.only();
}
/**
* 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 of {@code timeout()} method can be a code smell - there are better ways of testing concurrent code.
*
* See also {@link #after(long)} method for testing async code.
* Differences between {@code timeout()} and {@code after} are explained in Javadoc for {@link #after(long)}.
*
*
* //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();
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - duration in milliseconds
*
* @return object that allows fluent specification of the verification (times(x), atLeast(y), etc.)
*/
public static VerificationWithTimeout timeout(long millis) {
return new Timeout(millis, VerificationModeFactory.times(1));
}
/**
* 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 of {@code after()} method can be a code smell - there are better ways of testing concurrent code.
*
* Not yet implemented to work with InOrder verification.
*
* See also {@link #timeout(long)} method for testing async code.
* Differences between {@code timeout()} and {@code after()} are explained below.
*
*
* //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() vs. after()
*
*
timeout() exits immediately with success when verification passes
*
after() awaits full duration to check if verification passes
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - duration in milliseconds
*
* @return object that allows fluent specification of the verification
*/
public static VerificationAfterDelay after(long millis) {
return new After(millis, VerificationModeFactory.times(1));
}
/**
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ: https://github.com/mockito/mockito/wiki/FAQ
*
* 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:
*
* //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);
*
*
* 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.
*
* Sometimes though, you might want to validate the framework usage explicitly.
* For example, one of the users wanted to put validateMockitoUsage() in his @After method
* 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 having validateMockitoUsage() in @After is 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: {@link MockitoJUnitRunner} and rule: {@link MockitoRule} do 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 @After has zero cost.
*
* See examples in javadoc for {@link Mockito} class
*/
public static void validateMockitoUsage() {
MOCKITO_CORE.validateMockitoUsage();
}
/**
* 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));
*
* {@link MockSettings} has 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 {@link MockSettings} to learn about possible mock settings.
*
*
* @return mock settings instance with defaults.
*/
public static MockSettings withSettings() {
return new MockSettingsImpl().defaultAnswer(RETURNS_DEFAULTS);
}
/**
* Adds a description to be printed if verification fails.
*
* verify(mock, description("This will print on failure")).someMethod("some arg");
*
* @param description The description to print on failure.
* @return verification mode
* @since 2.1.0
*/
public static VerificationMode description(String description) {
return times(1).description(description);
}
/**
* For advanced users or framework integrators. See {@link MockitoFramework} class.
*
* @since 2.1.0
*/
public static MockitoFramework framework() {
return new DefaultMockitoFramework();
}
/**
* {@code MockitoSession} is 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 {@link MockitoSession}.
*
* @since 2.7.0
*/
public static MockitoSessionBuilder mockitoSession() {
return new DefaultMockitoSessionBuilder();
}
/**
* Lenient stubs bypass "strict stubbing" validation (see {@link Strictness#STRICT_STUBS}).
* When stubbing is declared as lenient, it will not be checked for potential stubbing problems such as
* 'unnecessary stubbing' ({@link UnnecessaryStubbingException}) or for 'stubbing argument mismatch' {@link PotentialStubbingProblem}.
*
*
* lenient().when(mock.foo()).thenReturn("ok");
*
*
* Most mocks in most tests don't need leniency and should happily prosper with {@link Strictness#STRICT_STUBS}.
*
*
If a specific stubbing needs to be lenient - use this method
*
If a specific mock need to have lenient stubbings - use {@link MockSettings#strictness(Strictness)}
*
If a specific test method / test class needs to have all stubbings lenient
* - configure strictness using our JUnit support ({@link MockitoJUnit} or Mockito Session ({@link 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();
* }
* }
*