|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||
java.lang.Objectorg.mockito.Matchers
org.mockito.Mockito
public class Mockito
Enables mocks creation, verification and stubbing.
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);
//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.
Click here to see more built-in matchers
and examples of custom argument matchers / hamcrest matchers.
Warning:
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.
//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, stubVoid(Object) was used for stubbing voids.
Currently stubVoid() is deprecated in favor of doThrow(Throwable).
This is because of improved readability and consistency with the family of doAnswer(Answer) methods.
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");
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);
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 never() - it is more explicit and
communicates an intent well.
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 runners
MockitoJUnitRunner, MockitoJUnit44Runner.
Read more here: MockitoAnnotations
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:
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"));
Answer interface.
Yet another controversial feature which was not included in Mockito originally. We recommend using simple stubbing with toReturn() or toThrow() 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"));
when(Object) because the compiler does not like void methods inside brackets...
doThrow(Throwable) replaces the 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();Read more about other methods:
Real spies should be used carefully and occasionally, for example when dealing with legacy code.
Spying on real objects is often associated with "partial mocking" concept. However, Mockito spies are not partial mocks. Mockito spy is meant to help testing other classes - not the spy itself. Therefore spy will not help if you intend to verify if method calls other method on the same object. In this case I suggest being OO/SRPy (for example you might extract new class/interface...)
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");
when(Object) for stubbing spies. 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);
| Constructor Summary | |
|---|---|
Mockito()
|
|
| Method Summary | ||
|---|---|---|
static VerificationMode |
atLeast(int minNumberOfInvocations)
Allows at-least-x verification. |
|
static VerificationMode |
atLeastOnce()
Allows at-least-once verification. |
|
static VerificationMode |
atMost(int maxNumberOfInvocations)
Allows at-most-x verification. |
|
static Stubber |
doAnswer(Answer answer)
Use doAnswer() when you want to stub a void method with generic Answer. |
|
static Stubber |
doNothing()
Use doNothing() for setting void methods to do nothing. |
|
static Stubber |
doReturn(java.lang.Object toBeReturned)
Use doReturn() in those rare occasions when you cannot use when(Object). |
|
static Stubber |
doThrow(java.lang.Throwable toBeThrown)
Use doThrow() when you want to stub the void method with an exception. |
|
static InOrder |
inOrder(java.lang.Object... mocks)
Creates InOrder object that allows verifying mocks in order. |
|
static
|
mock(java.lang.Class<T> classToMock)
Creates mock object of given class or interface. |
|
static
|
mock(java.lang.Class<T> classToMock,
java.lang.String name)
Creates mock with a name. |
|
static VerificationMode |
never()
Alias to times(0), see times(int) |
|
static
|
spy(T object)
Creates a spy of the real object. |
|
static
|
stub(T methodCall)
Deprecated. |
|
static
|
stubVoid(T mock)
Deprecated. Use doThrow(Throwable) method for stubbing voids |
|
static VerificationMode |
times(int wantedNumberOfInvocations)
Allows verifying exact number of invocations. |
|
static
|
verify(T mock)
Verifies certain behavior happened once |
|
static
|
verify(T mock,
VerificationMode mode)
Verifies certain behavior happened at least once / exact number of times / never. |
|
static void |
verifyNoMoreInteractions(java.lang.Object... mocks)
Checks if any of given mocks has any unverified interaction. |
|
static void |
verifyZeroInteractions(java.lang.Object... mocks)
Verifies that no interactions happened on given mocks. |
|
static
|
when(T methodCall)
Enables stubbing methods. |
|
| Methods inherited from class org.mockito.Matchers |
|---|
anyBoolean, anyByte, anyChar, anyCollection, anyDouble, anyFloat, anyInt, anyList, anyLong, anyMap, anyObject, anyShort, anyString, argThat, booleanThat, byteThat, charThat, contains, doubleThat, endsWith, eq, eq, eq, eq, eq, eq, eq, eq, eq, floatThat, intThat, isA, isNotNull, isNull, longThat, matches, notNull, refEq, same, shortThat, startsWith |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
|---|
public Mockito()
| Method Detail |
|---|
public static <T> T mock(java.lang.Class<T> classToMock)
See examples in javadoc for Mockito class
classToMock - class or interface to mock
public static <T> T mock(java.lang.Class<T> classToMock,
java.lang.String name)
Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators. If you have too many mocks then refactor the code so that it's easy to test/debug without necessity of naming mocks.
If you use @Mock annotation then you've got naming mocks for free! @Mock uses field name as mock name. Read more.
See examples in javadoc for Mockito class
classToMock - class or interface to mock
public static <T> T spy(T object)
Real spies should be used carefully and occasionally, for example when dealing with legacy code.
Spying on real objects is often associated with "partial mocking" concept. However, Mockito spies are not partial mocks. Mockito spy is meant to help testing other classes - not the spy itself. Therefore spy will not help if you intend to verify if method calls other method on the same object. In this case I suggest being OO/SRPy (for example you might extract new class/interface...)
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");
when(Object) for stubbing spies. 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);
See examples in javadoc for Mockito class
object - to spy on
@Deprecated public static <T> DeprecatedOngoingStubbing<T> stub(T methodCall)
//Instead of: stub(mock.count()).toReturn(10); //Please do: when(mock.count()).thenReturn(10);Many users found stub() confusing therefore stub() has been deprecated in favor of
when(Object)
How to fix deprecation warnings? Typically it's just few minutes of search & replace job:
Mockito.stub; replace with: Mockito.when; stub( replace with: when( .toReturn( replace with: .thenReturn( .toThrow( replace with: .thenThrow( .toAnswer( replace with: .thenAnswer(If you're an existing user then sorry for making your code littered with deprecation warnings. This change was required to make Mockito better.
methodCall - method call
public static <T> NewOngoingStubbing<T> when(T methodCall)
Simply put: "When the x method is called then return y".
when() is a successor of deprecated stub(Object)
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");
For stubbing void methods with throwables see: doThrow(Throwable)
Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it.
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.
See examples in javadoc for Mockito class
methodCall - method to be stubbedpublic static <T> T verify(T mock)
Alias to verify(mock, times(1)) E.g:
verify(mock).someMethod("some arg");
Above is equivalent to:
verify(mock, times(1)).someMethod("some arg");
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.
See examples in javadoc for Mockito class
mock - to be verified
public static <T> T verify(T mock,
VerificationMode mode)
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
See examples in javadoc for Mockito class
mock - to be verifiedmode - times(x), atLeastOnce() or never()
public static void verifyNoMoreInteractions(java.lang.Object... mocks)
You can use this method after you verified your mocks - to make sure that nothing else was invoked on your mocks.
See also never() - it is more explicit and communicates an intent well.
Stubbed invocations (if called) are also treated as interactions.
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.
Example:
//interactions mock.doSomething(); mock.doSomethingUnexpected(); //verification verify(mock).doSomething(); //following will fail because 'doSomethingUnexpected()' is unexpected verifyNoMoreInteractions(mock);See examples in javadoc for
Mockito class
mocks - to be verifiedpublic static void verifyZeroInteractions(java.lang.Object... mocks)
verifyZeroInteractions(mockOne, mockTwo);See examples in javadoc for
Mockito class
mocks - to be verifiedpublic static <T> VoidMethodStubbable<T> stubVoid(T mock)
doThrow(Throwable) method for stubbing voids
//Instead of: stubVoid(mock).toThrow(e).on().someVoidMethod(); //Please do: doThrow(e).when(mock).someVoidMethod();doThrow() replaces stubVoid() because of improved readability and consistency with the family of doAnswer() methods.
Originally, stubVoid() was used for stubbing void methods with exceptions. E.g:
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();See examples in javadoc for
Mockito class
mock - to stub
public static Stubber doThrow(java.lang.Throwable toBeThrown)
Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...
Example:
doThrow(new RuntimeException()).when(mock).someVoidMethod();
toBeThrown - to be thrown when the stubbed method is called
public static Stubber doAnswer(Answer answer)
Answer.
Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...
Example:
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Mock mock = invocation.getMock();
return null;
}})
.when(mock).someMethod();
answer - to answer when the stubbed method is called
public static Stubber doNothing()
1. 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();2. 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();
public static Stubber doReturn(java.lang.Object toBeReturned)
when(Object).
Beware that when(Object) is always recommended for stubbing because it is argument type-safe
and more readable (especially when stubbing consecutive calls).
Here are those rare occasions when doReturn() comes handy:
1. 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);
2. 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 ellegant syntax. Note that the scenarios are very rare, though.
Spying should be sporadic and overriding exception-stubbing is very rare.
toBeReturned - to be returned when the stubbed method is called
public static InOrder inOrder(java.lang.Object... mocks)
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.
See examples in javadoc for Mockito class
mocks - to be verified in order
public static VerificationMode times(int wantedNumberOfInvocations)
verify(mock, times(2)).someMethod("some arg");
See examples in javadoc for Mockito class
wantedNumberOfInvocations - wanted number of invocations
public static VerificationMode never()
times(int)
Verifies that interaction did not happen. E.g:
verify(mock, never()).someMethod();
See examples in javadoc for Mockito class
public static VerificationMode atLeastOnce()
verify(mock, atLeastOnce()).someMethod("some arg");
Alias to atLeast(1)
See examples in javadoc for Mockito class
public static VerificationMode atLeast(int minNumberOfInvocations)
verify(mock, atLeast(3)).someMethod("some arg");
See examples in javadoc for Mockito class
minNumberOfInvocations - minimum number of invocations
public static VerificationMode atMost(int maxNumberOfInvocations)
verify(mock, atMost(3)).someMethod("some arg");
See examples in javadoc for Mockito class
maxNumberOfInvocations - max number of invocations
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||