/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito; import org.mockito.internal.MockitoCore; import org.mockito.internal.creation.MockSettingsImpl; import org.mockito.internal.debugging.MockitoDebuggerImpl; import org.mockito.internal.stubbing.answers.*; import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues; import org.mockito.internal.stubbing.defaultanswers.ReturnsMoreEmptyValues; import org.mockito.internal.verification.VerificationModeFactory; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.*; import org.mockito.verification.Timeout; import org.mockito.verification.VerificationMode; import org.mockito.verification.VerificationWithTimeout; /** *
* Mockito library enables mocks creation, verification and stubbing. ** This javadoc content is also available on the http://mockito.org web page. * All documentation is kept in javadocs because it guarantees consistency between what's on the web and what's in the source code. * Also, it makes possible to access documentation straight from the IDE even if you work offline. * *
@Mock
annotation doReturn()
|doThrow()
|doAnswer()
|doNothing()
|doCallRealMethod()
family of methods@Captor
, @Spy
, @InjectMocks
(Since 1.8.3) @Spies
, @InjectMocks
and constructor injection goodness (Since 1.9.0)MockMaker
API (Since 1.9.5)
* Following examples mock a List, because everyone knows its interface (methods
* like add()
, get()
, clear()
will be used).
* You probably wouldn't mock List class 'in real'.
*
*
*
*
*
* //Let's import Mockito statically so that the code looks clearer
* import static org.mockito.Mockito.*;
*
* //mock creation
* List mockedList = mock(List.class);
*
* //using mock object
* mockedList.add("one");
* mockedList.clear();
*
* //verification
* verify(mockedList).add("one");
* verify(mockedList).clear();
*
*
* * Once created, mock will remember all interactions. Then you can selectively * verify whatever interaction you are interested in. * * * * *
* //You can mock concrete classes, not only 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 before even verify() gets executed).
* //If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.
* verify(mockedList).get(0);
*
*
* 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 hamcrest (let's say isValid() returns your own hamcrest matcher):
* when(mockedList.contains(argThat(isValid()))).thenReturn("element");
*
* //following prints "element"
* System.out.println(mockedList.get(999));
*
* //you can also verify using an argument matcher
* verify(mockedList).get(anyInt());
*
*
* * Argument matchers allow flexible verification or stubbing. * {@link Matchers Click 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 & 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. *
* E.g: (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 anyObject()
, eq()
do not return matchers.
* Internally, they record a matcher on a stack and return a dummy value (usually null).
* This implementation is due static type safety imposed by java compiler.
* The consequence is that you cannot use anyObject()
, eq()
methods outside of verified/stubbed method.
*
*
*
*
*
* //using mock
* mockedList.add("once");
*
* mockedList.add("twice");
* mockedList.add("twice");
*
* mockedList.add("three times");
* mockedList.add("three times");
* mockedList.add("three times");
*
* //following two verifications work exactly the same - times(1) is used by default
* verify(mockedList).add("once");
* verify(mockedList, times(1)).add("once");
*
* //exact number of invocations verification
* verify(mockedList, times(2)).add("twice");
* verify(mockedList, times(3)).add("three times");
*
* //verification using never(). never() is an alias to times(0)
* verify(mockedList, never()).add("never happened");
*
* //verification using atLeast()/atMost()
* verify(mockedList, atLeastOnce()).add("three times");
* verify(mockedList, atLeast(2)).add("five times");
* verify(mockedList, atMost(5)).add("three times");
*
*
*
* * times(1) is the default. Therefore using times(1) explicitly can be * omitted. * * * * *
* doThrow(new RuntimeException()).when(mockedList).clear();
*
* //following throws RuntimeException:
* mockedList.clear();
*
*
* Read more about doThrow|doAnswer family of methods in paragraph 12.
*
* Initially, {@link Mockito#stubVoid(Object)} was used for stubbing voids.
* Currently stubVoid()
is deprecated in favor of {@link Mockito#doThrow(Throwable)}.
* This is because of improved readability and consistency with the family of {@link Mockito#doAnswer(Answer)} methods.
*
*
*
*
*
* // 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 InOrder object passing only 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");
*
* //verify that other mocks were not interacted
* verifyZeroInteractions(mockTwo, mockThree);
*
*
*
*
*
*
*
* //using mocks
* mockedList.add("one");
* mockedList.add("two");
*
* verify(mockedList).add("one");
*
* //following verification will fail
* verifyNoMoreInteractions(mockedList);
*
*
* 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. You can find further reading
* here.
*
* * See also {@link Mockito#never()} - it is more explicit and * communicates the intent well. *
* * * * *
@Mock
annotation
* public class ArticleManagerTest {
*
* @Mock private ArticleCalculator calculator;
* @Mock private ArticleDatabase database;
* @Mock private UserProvider userProvider;
*
* private ArticleManager manager;
*
*
* Important! This needs to be somewhere in the base class or a test
* runner:
*
*
* MockitoAnnotations.initMocks(testClass);
*
*
* You can use built-in runner: {@link MockitoJUnitRunner}.
* * Read more here: {@link MockitoAnnotations} * * * * *
* *
* when(mock.someMethod("some arg"))
* .thenThrow(new RuntimeException())
* .thenReturn("foo");
*
* //First call: throws runtime exception:
* mock.someMethod("some arg");
*
* //Second call: prints "foo"
* System.out.println(mock.someMethod("some arg"));
*
* //Any consecutive call: prints "foo" as well (last stubbing wins).
* System.out.println(mock.someMethod("some arg"));
*
*
* Alternative, shorter version of consecutive stubbing:
*
*
* when(mock.someMethod("some arg"))
* .thenReturn("one", "two", "three");
*
*
*
*
*
*
* Yet another controversial feature which was not included in Mockito
* originally. We recommend using simple stubbing with thenReturn()
or
* thenThrow()
only. Those two should be just enough to test/test-drive
* any clean & simple code.
*
*
* when(mock.someMethod(anyString())).thenAnswer(new Answer() {
* Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Object mock = invocation.getMock();
* return "called with arguments: " + args;
* }
* });
*
* //Following prints "called with arguments: foo"
* System.out.println(mock.someMethod("foo"));
*
*
*
*
*
* doReturn()
|doThrow()
|
* doAnswer()
|doNothing()
|doCallRealMethod()
family of methods
* {@link Mockito#doThrow(Throwable)} replaces the {@link Mockito#stubVoid(Object)} method for stubbing voids.
* The main reason is improved readability and consistency with the family of doAnswer()
methods.
*
* Use doThrow()
when you want to stub a void method with an exception:
*
* doThrow(new RuntimeException()).when(mockedList).clear();
*
* //following throws RuntimeException:
* mockedList.clear();
*
*
*
* 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
*
when()
, for all of your stubbing calls.
* * Read more about these methods: *
* {@link Mockito#doReturn(Object)} *
* {@link Mockito#doThrow(Throwable)} *
* {@link Mockito#doThrow(Class)} *
* {@link Mockito#doAnswer(Answer)} *
* {@link Mockito#doNothing()} *
* {@link Mockito#doCallRealMethod()} * * * * *
* Real spies should be used carefully and occasionally, for example when dealing with legacy code. * *
* Spying on real objects can be associated with "partial mocking" concept. * Before the release 1.8, Mockito spies were not real partial mocks. * The reason was we thought partial mock is a code smell. * At some point we found legitimate use cases for partial mocks * (3rd party interfaces, interim refactoring of legacy code, the full article is here) *
* *
* 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");
*
*
* 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);
*
* * It is the default answer so it will be used only when you don't stub the method call. * *
* Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
*
*
* * Read more about this interesting implementation of Answer: {@link Mockito#RETURNS_SMART_NULLS} * * * * *
equals()
method.
* This is also the recommended way of matching arguments because it makes tests clean & simple.
* In some situations though, it is helpful to assert on certain arguments after the actual verification.
* For example:
*
* ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
* verify(mock).doSomething(argument.capture());
* assertEquals("John", argument.getValue().getName());
*
*
* 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 where passed to mocks. * However, ArgumentCaptor may be a better fit if: *
* Before release 1.8 spy()
was not producing real partial mocks and it was confusing for some users.
* Read more about spying: here or in javadoc for {@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 & well-designed code. * * * * *
* Instead of reset()
please consider writing simple, small and focused test methods over lengthy, over-specified tests.
* First potential code smell is reset()
in the middle of the test method. This probably means you're testing too much.
* Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
* There are several threads about it on mockito mailing list.
*
* The only reason we added reset()
method is to
* make it possible to work with container-injected mocks.
* See issue 55 (here)
* or 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 & stubbing
*
*
*
*
*
* * In case of questions you may also post to mockito mailing list: * http://groups.google.com/group/mockito *
* 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()} * * * * *
* Start learning about BDD here: http://en.wikipedia.org/wiki/Behavior_Driven_Development *
* 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! *
* Here is how the test might look like: *
* import static org.mockito.BDDMockito.*;
*
* Seller seller = mock(Seller.class);
* Shop shop = new Shop(seller);
*
* public void shouldBuyBread() throws Exception {
* //given
* given(seller.askForBread()).willReturn(new Bread());
*
* //when
* Goods goods = shop.buyBread();
*
* //then
* assertThat(goods, containBread());
* }
*
*
*
*
*
* * 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());
*
* * The mock can be serialized assuming all the normal * serialization requirements are met by the class. *
* Making a real object spy serializable is a bit more effort as the spy(...) method does not have an overloaded version * which accepts MockSettings. No worries, you will hardly ever use it. * *
* List<Object> list = new ArrayList<Object>();
* List<Object> spy = mock(ArrayList.class, withSettings()
* .spiedInstance(list)
* .defaultAnswer(CALLS_REAL_METHODS)
* .serializable());
*
*
*
*
*
* @Captor
,
* @Spy
,
* @InjectMocks
(Since 1.8.3)* Release 1.8.3 brings new annotations that may be helpful on occasion: * *
* Note that @{@link InjectMocks} can only be used in combination with the @{@link Spy} annotation, it means * that Mockito will inject mocks in a partial mock under testing. As a remainder, please read point 16 about partial mocks. * *
* All new annotations are *only* processed on {@link MockitoAnnotations#initMocks(Object)}. * Just like for @{@link Mock} annotation you can use the built-in runner: {@link MockitoJUnitRunner}. *
* * * * *
* 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. *
* It feels 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 within given time span
* verify(mock, timeout(100)).someMethod();
* //above is an alias to:
* verify(mock, timeout(100).times(1)).someMethod();
*
* //passes when someMethod() is called *exactly* 2 times within given time span
* verify(mock, timeout(100).times(2)).someMethod();
*
* //passes when someMethod() is called *at least* 2 times within given time span
* verify(mock, timeout(100).atLeast(2)).someMethod();
*
* //verifies someMethod() within given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
*
*
*
*
*
* @Spies
,
* @InjectMocks
and constructor injection goodness (Since 1.9.0)* 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#initMocks(Object)} or {@link MockitoJUnitRunner}. *
* 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 & 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...)}
*
Some examples: *
* verify(mock).foo();
* verify(mockTwo).bar();
*
* //ignores all stubbed methods:
* verifyNoMoreInvocations(ignoreStubs(mock, mockTwo));
*
* //creates InOrder that will ignore stubbed
* InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo));
* inOrder.verify(mock).foo();
* inOrder.verify(mockTwo).bar();
* inOrder.verifyNoMoreInteractions();
*
* * Advanced examples and more details can be found in javadoc for {@link Mockito#ignoreStubs(Object...)} * * * * *
* To identify whether a particular object is a mock or a spy: *
* Mockito.mockingDetails(someObject).isMock();
* Mockito.mockingDetails(someObject).isSpy();
*
* Both the {@link MockingDetails#isMock} and {@link MockingDetails#isSpy()} methods return boolean
.
* As a spy is just a different kind of mock, isMock()
returns true if the object is a spy.
* In future Mockito versions MockingDetails may grow and provide other useful information about the mock,
* e.g. invocations, stubbing info, etc.
*
*
*
*
* Useful for spies or partial mocks of objects that are difficult to mock or spy using the usual spy API. * Possible use cases: *
The difference with the regular spy: *
* See more information in docs for {@link AdditionalAnswers#delegatesTo(Object)}. * * * * *
MockMaker
API (Since 1.9.5)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 cglib 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}.
*
*/
@SuppressWarnings("unchecked")
public class Mockito extends Matchers {
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 unstubbed invocations. *
* This implementation first tries the global configuration. * If there is no global configuration then it uses {@link ReturnsEmptyValues} (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();
*
*
*
* * How deep stub work internally? *
* //this:
* Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);
* when(mock.getBar().getName(), "deep");
*
* //is equivalent of
* Foo foo = mock(Foo.class);
* Bar bar = mock(Bar.class);
* when(foo.getBar()).thenReturn(bar);
* when(bar.getName()).thenReturn("deep");
*
*
*
* * This feature will not work when any return type of methods included in the chain cannot be mocked * (for example: is a primitive or a final class). This is because of java type system. *
*/ public static final AnswerAnswer
to be used with {@link Mockito#mock(Class, Answer)}
* * {@link Answer} can be used to define the return values of unstubbed invocations. *
* This implementation can be helpful when working with legacy code. * When this implementation is used, unstubbed 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 less tackling complexity by dividing the complexity into separate, specific, SRPy objects. * How does partial mock fit into this paradigm? Well, it just doesn't... * Partial mock usually means that the complexity has been moved to a different method on the same object. * In most cases, this is not the way you want to design your application. *
* However, there are rare cases when partial mocks come handy: * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) * However, I wouldn't use partial mocks for new, test-driven & well-designed code. *
* Example: *
* Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
*
* // this calls the real implementation of Foo.getSomething()
* value = mock.getSomething();
*
* when(mock.getSomething()).thenReturn(fakeValue);
*
* // now fakeValue is returned
* value = mock.getSomething();
*
*/
public static final Answer
* See examples in javadoc for {@link Mockito} class
*
* @param classToMock class or interface to mock
* @return mock object
*/
public static
* 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
*
* 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
* 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
* @return A {@link org.mockito.MockingDetails} instance.
* @since 1.9.5
*/
@Incubating
public static MockingDetails mockingDetails(Object toInspect) {
return MOCKITO_CORE.mockingDetails(toInspect);
}
/**
* Deprecated : Please use mock(Foo.class, defaultAnswer);
*
* See {@link Mockito#mock(Class, Answer)}
*
* Why it is deprecated? ReturnValues is being replaced by Answer
* for better consistency & interoperability of the framework.
* Answer interface has been in Mockito for a while and it has the same responsibility as ReturnValues.
* There's no point in mainting exactly the same interfaces.
*
* Creates mock with a specified strategy for its return values.
* It's quite advanced feature and typically you don't need it to write decent tests.
* However it can be helpful when working with legacy systems.
*
* Obviously return values are used only when you don't stub the method call.
*
* See examples in javadoc for {@link Mockito} class
* It is the default answer so it will be used only when you don't stub the method call.
*
* See examples in javadoc for {@link Mockito} class
* The number of configuration points for a mock grows
* so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.
* Hence {@link MockSettings}.
*
* 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
* 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 is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
*
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
*
* Example:
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param object
* to spy on
* @return a spy of the real object
*/
public static
* Some users find stub() confusing therefore {@link Mockito#when(Object)} is recommended over stub()
*
* Stubbing can be overridden: for example common stubbing can go to fixture
* setup but the test methods can override it.
* Please note that overridding stubbing is a potential code smell that points out too much stubbing.
*
* Once stubbed, the method will always return 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.
* Not convinced? See here.
*
* @param methodCall
* method call
* @return DeprecatedOngoingStubbing object to set stubbed value/exception
*/
public static
* Simply put: "When the x method is called then return y".
*
* when() is a successor of deprecated {@link Mockito#stub(Object)}
*
* Examples:
*
*
* Stubbing can be overridden: for example common stubbing can go to fixture
* setup but the test methods can override it.
* Please note that overridding stubbing is a potential code smell that points out too much stubbing.
*
* Once stubbed, the method will always return 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
* 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
* Alias to
* Arguments passed are compared using
* Although it is possible to verify a stubbed invocation, usually it's just redundant.
* Let's say you've stubbed
* See examples in javadoc for {@link Mockito} class
*
* @param mock to be verified
* @return mock object itself
*/
public static
* Arguments passed are compared using
*
* @param mock to be verified
* @param mode times(x), atLeastOnce() or never()
*
* @return mock object itself
*/
public static
* Instead of
* The only reason we added
* Don't harm yourself.
* 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.
*
* A word of warning:
* Some users who did a lot of classic, expect-run-verify mocking tend to use
* This method will also detect unverified invocations that occurred before the test method,
* for example: in
* Example:
*
*
* 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
*/
public static void verifyZeroInteractions(Object... mocks) {
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
/**
*
* Originally,
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets...
*
* Example:
*
*
* 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...
*
* Example:
*
*
* As usual you are going to read the partial mock warning:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
*
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
*
* 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:
*
* 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.doAnswer(new CallsRealMethods());
}
/**
* Use
* Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets...
*
* Example:
*
*
* 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.doAnswer(answer);
}
/**
* Use
*
* See examples in javadoc for {@link Mockito} class
*
* @return stubber - to select a method for stubbing
*/
public static Stubber doNothing() {
return MOCKITO_CORE.doAnswer(new DoesNothing());
}
/**
* Use
* 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:
*
*
*
* 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.doAnswer(new Returns(toBeReturned));
}
/**
* Creates {@link org.mockito.InOrder} object that allows verifying mocks in order.
*
*
* Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
*
*
* As of Mockito 1.8.4 you can verifyNoMoreInvocations() 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.
* Sometimes useful when coupled with
* Warning,
* 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:
*
* Verifies that interaction did not happen. E.g:
*
* If you want to verify there were NO interactions with the mock
* check out {@link Mockito#verifyZeroInteractions(Object...)}
* or {@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
*
* @return verification mode
*/
public static VerificationMode atLeastOnce() {
return VerificationModeFactory.atLeastOnce();
}
/**
* Allows at-least-x verification. E.g:
*
* See also {@link Mockito#verifyNoMoreInteractions(Object...)}
*
* See examples in javadoc for {@link Mockito} class
*
* @return verification mode
*/
public static VerificationMode only() {
return VerificationModeFactory.only();
}
/**
* 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.
*
* It feels 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.
*
* In case of questions you may also post to mockito mailing list: http://groups.google.com/group/mockito
*
*
* Examples of incorrect use:
*
* Sometimes though, you might want to validate the framework usage explicitly.
* For example, one of the users wanted to put
* Built-in runner: {@link MockitoJUnitRunner} does validateMockitoUsage() after each test method.
*
* Bear in mind that usually you don't have to
* 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 & maintainable code.
* If you cannot write a test in a simple way - refactor the code under test.
*
* Examples of mock settings:
*
* 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);
}
/**
* Helps debugging failing tests. Experimental - use at your own risk. We're not sure if this method will stay in public api.
*/
@Deprecated
static MockitoDebugger debug() {
return new MockitoDebuggerImpl();
}
}
@Mock
annotation then you've got naming mocks for free! @Mock
uses field name as mock name. {@link Mock Read more.}
*
*
*
* Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnReturnValues());
*
*
*
* Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);
* Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
*
* 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 it is testable in a simple way?
*
* Listener mock = mock(Listener.class, withSettings()
* .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));
* );
*
*
*
* 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!
*
*
* 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);
*
*
* stub(mock.someMethod()).toReturn(10);
*
* //you can use flexible argument matchers, e.g:
* stub(mock.someMethod(anyString())).toReturn(10);
*
* //setting exception to be thrown:
* stub(mock.someMethod("some arg")).toThrow(new RuntimeException());
*
* //you can stub with different behavior for consecutive method calls.
* //Last stubbing (e.g: toReturn("foo")) determines the behavior for further consecutive calls.
* stub(mock.someMethod("some arg"))
* .toThrow(new RuntimeException())
* .toReturn("foo");
*
* For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable)}
*
* //Instead of:
* stub(mock.count()).toReturn(10);
*
* //You can do:
* when(mock.count()).thenReturn(10);
*
*
* For stubbing void methods with throwables see: {@link Mockito#doThrow(Throwable)}
*
* 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();
*
*
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.
* Not convinced? See here.
*
* verify(mock, times(1))
E.g:
*
* Above is equivalent to:
*
* verify(mock).someMethod("some arg");
*
*
* verify(mock, times(1)).someMethod("some arg");
*
equals()
method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
* 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.
* Not convinced? See here.
*
*
*
* times(1) is the default and can be omitted
*
* 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());
*
equals()
method.
* Read about {@link ArgumentCaptor} or {@link ArgumentMatcher} to find out other ways of matching / asserting arguments passed.
* #reset()
please consider writing simple, small and focused test methods over lengthy, over-specified tests.
* First potential code smell is reset()
in the middle of the test method. This probably means you're testing too much.
* Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
* There are several threads about it on mockito mailing list.
* reset()
method is to
* make it possible to work with container-injected mocks.
* See issue 55 (here)
* or FAQ (here).
* reset()
in the middle of the test method is a code smell (you're probably testing too much).
*
*
* @param
* List mock = mock(List.class);
* when(mock.size()).thenReturn(10);
* mock.add(1);
*
* reset(mock);
* //at this point the mock forgot any interactions & stubbing
*
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. You can find further reading
* here.
* setUp()
, @Before
method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
*
*
*
* 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.
*
* //interactions
* mock.doSomething();
* mock.doSomethingUnexpected();
*
* //verification
* verify(mock).doSomething();
*
* //following will fail because 'doSomethingUnexpected()' is unexpected
* verifyNoMoreInteractions(mock);
*
*
* This method will also detect invocations
* that occurred before the test method, for example: in
* verifyZeroInteractions(mockOne, mockTwo);
*
setUp()
, @Before
method or in constructor.
* Consider writing nice code that makes interactions only in test methods.
*
*
* doThrow() replaces stubVoid() because of improved readability and consistency with the family of doAnswer() methods.
*
* //Instead of:
* stubVoid(mock).toThrow(e).on().someVoidMethod();
*
* //Please do:
* doThrow(e).when(mock).someVoidMethod();
*
stubVoid()
was used for stubbing void methods with exceptions. E.g:
*
*
*
* See examples in javadoc for {@link Mockito} class
*
* @deprecated Use {@link Mockito#doThrow(Throwable)} method for stubbing voids
*
* @param mock
* to stub
* @return stubbable object that allows stubbing with throwable
*/
public static
* stubVoid(mock).toThrow(new RuntimeException()).on().someMethod();
*
* //you can stub with different behavior for consecutive calls.
* //Last stubbing (e.g. toReturn()) determines the behavior for further consecutive calls.
* stubVoid(mock)
* .toThrow(new RuntimeException())
* .toReturn()
* .on().someMethod();
*
doThrow()
when you want to stub the void method with an exception.
*
*
* @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.doAnswer(new ThrowsException(toBeThrown));
}
/**
* Use
* doThrow(new RuntimeException()).when(mock).someVoidMethod();
*
doThrow()
when you want to stub the void method to throw exception of specified class.
*
*
* @param toBeThrown to be thrown when the stubbed method is called
* @return stubber - to select a method for stubbing
* @since 1.9.0
*/
public static Stubber doThrow(Class extends Throwable> toBeThrown) {
return MOCKITO_CORE.doAnswer(new ThrowsExceptionClass(toBeThrown));
}
/**
* Use
* doThrow(RuntimeException.class).when(mock).someVoidMethod();
*
doCallRealMethod()
when you want to call the real implementation of a method.
*
*
* Foo mock = mock(Foo.class);
* doCallRealMethod().when(mock).someVoidMethod();
*
* // this will call the real implementation of Foo.someVoidMethod()
* mock.someVoidMethod();
*
doAnswer()
when you want to stub a void method with generic {@link Answer}.
*
*
* doAnswer(new Answer() {
* public Object answer(InvocationOnMock invocation) {
* Object[] args = invocation.getArguments();
* Mock mock = invocation.getMock();
* return null;
* }})
* .when(mock).someMethod();
*
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:
*
*
*
*
* doNothing().
* doThrow(new RuntimeException())
* .when(mock).someVoidMethod();
*
* //does nothing the first time:
* mock.someVoidMethod();
*
* //throws RuntimeException the next time:
* mock.someVoidMethod();
*
*
* 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();
*
doReturn()
in those rare occasions when you cannot use {@link Mockito#when(Object)}.
*
*
*
* 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
* overridding stubbing is a potential code smell that points out too much stubbing.
*
*
* 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);
*
*
* 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();
*
*
* Verification in order is flexible - you don't have to verify all interactions one-by-one
* but only those that you are interested in testing in order.
*
* InOrder inOrder = inOrder(firstMock, secondMock);
*
* inOrder.verify(firstMock).add("was called first");
* inOrder.verify(secondMock).add("was called second");
*
InOrder
verification is 'greedy'. You will hardly every notice it but
* if you want to find out more search for 'greedy' on the Mockito
* wiki pages.
* verifyNoMoreInteractions()
or verification inOrder()
.
* Helps avoiding redundant verification of stubbed calls - typically we're not interested in verifying stubs.
* 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().
*
* Ignoring stubs can be used with verification in order:
*
* //mocking lists for the sake of the example (if you mock List in real you will burn in hell)
* List mock1 = mock(List.class), mock2 = mock(List.class);
*
* //stubbing mocks:
* when(mock1.get(0)).thenReturn(10);
* when(mock2.get(0)).thenReturn(20);
*
* //using mocks by calling stubbed get(0) methods:
* System.out.println(mock1.get(0)); //prints 10
* System.out.println(mock2.get(0)); //prints 20
*
* //using mocks by calling clear() methods:
* mock1.clear();
* mock2.clear();
*
* //verification:
* verify(mock1).clear();
* verify(mock2).clear();
*
* //verifyNoMoreInteractions() fails because get() methods were not accounted for.
* try { verifyNoMoreInteractions(mock1, mock2); } catch (NoInteractionsWanted e);
*
* //However, if we ignore stubbed methods then we can verifyNoMoreInteractions()
* verifyNoMoreInteractions(ignoreStubs(mock1, mock2));
*
* //Remember that ignoreStubs() *changes* the input mocks and returns them for convenience.
*
*
* @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:
*
* List list = mock(List.class);
* when(mock.get(0)).thenReturn("foo");
*
* list.add(0);
* System.out.println(list.get(0)); //we don't want to verify this
* list.clear();
*
* InOrder inOrder = inOrder(ignoreStubs(list));
* inOrder.verify(list).add(0);
* inOrder.verify(list).clear();
* inOrder.verifyNoMoreInteractions();
*
*
* 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
* verify(mock, times(2)).someMethod("some arg");
*
times(0)
, see {@link Mockito#times(int)}
*
*
*
* verify(mock, never()).someMethod();
*
* Alias to
* verify(mock, atLeastOnce()).someMethod("some arg");
*
atLeast(1)
.
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param minNumberOfInvocations minimum number of invocations
*
* @return verification mode
*/
public static VerificationMode atLeast(int minNumberOfInvocations) {
return VerificationModeFactory.atLeast(minNumberOfInvocations);
}
/**
* Allows at-most-x verification. E.g:
*
* verify(mock, atLeast(3)).someMethod("some arg");
*
*
* 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
*
* verify(mock, atMost(3)).someMethod("some arg");
*
*
* inOrder.verify( mock, calls( 2 )).someMethod( "some arg" );
*
*
* 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();
* verifyNoMoreInvocations(mock);
*
*
* See examples in javadoc for {@link Mockito} class
*
* @param millis - time span in millisecond
*
* @return verification mode
*/
public static VerificationWithTimeout timeout(int millis) {
return new Timeout(millis, VerificationModeFactory.times(1));
}
/**
* First of all, in case of any trouble, I encourage you to read the Mockito FAQ: http://code.google.com/p/mockito/wiki/FAQ
*
* //passes when someMethod() is called within given time span
* verify(mock, timeout(100)).someMethod();
* //above is an alias to:
* verify(mock, timeout(100).times(1)).someMethod();
*
* //passes when someMethod() is called *exactly* 2 times within given time span
* verify(mock, timeout(100).times(2)).someMethod();
*
* //passes when someMethod() is called *at least* 2 times within given time span
* verify(mock, timeout(100).atLeast(2)).someMethod();
*
* //verifies someMethod() within given time span using given verification mode
* //useful only if you have your own custom verification modes.
* verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();
*
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.
*
*
* 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.
*
* //Oups, someone forgot thenReturn() part:
* when(mock.get());
*
* //Oups, someone put the verified method call inside verify() where it should be outside:
* verify(mock.execute());
*
* //Oups, someone has used EasyMock for too long and forgot to specify the method to verify:
* verify(mock);
*
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 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.
* 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.
*
* {@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.
*
* //Creates mock with different default answer & name
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie"));
*
* //Creates mock with different default answer, descriptive name and extra interfaces
* Foo mock = mock(Foo.class, withSettings()
* .defaultAnswer(RETURNS_SMART_NULLS)
* .name("cool mockie")
* .extraInterfaces(Bar.class));
*