|
||||||||||
| 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 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 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 invocations. 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
stub(mockedList.get(0)).toReturn("first");
stub(mockedList.get(1)).toThrow(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));
//Stubbed invocations are verified implicitly. The execution flow of your own code does it completely for free.
//Although it is possible to verify a stubbed invocation, in majority of cases it's not necessary:
verify(mockedList).get(0);
//stubbing using built-in anyInt() argument matcher
stub(mockedList.get(anyInt())).toReturn("element");
//stubbing using hamcrest (let's say isValid() returns your own hamcrest matcher):
stub(mockedList.contains(argThat(isValid()))).toReturn("element");
//following prints "element"
System.out.println(mockedList.get(999));
//you can also verify using argument matcher
verify(mockedList).get(anyInt());
Argument matchers allow flexible verification or stubbing.
See the whole library of Matchers including 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 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 atLeastOnce()
verify(mockedList, atLeastOnce()).add("three times");
times(1) is the default. Therefore using times(1) explicitly can be omitted.
stubVoid(mockedList).toThrow(new RuntimeException()).on().clear(); //following throws exception mockedList.clear();
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 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);
//following works exactly the same as above
verifyNoMoreInteractions(mockTwo, mockThree);
See more verifyNoMoreInteractions(java.lang.Object...)
Instead of verifyZeroInteractions() you can call verifyNoMoreInteractions() but the first one is more explicit and can read better.
//using mocks
mockedList.add("one");
mockedList.add("two");
verify(mockedList).add("one");
//following verification will fail
verifyNoMoreInteractions(mockedList);
Remember that usually it's not necessary to call verifyNoMoreInteractions() all the time.
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);Examples how to write a junit test runner are in Mockito test code (mockito/test/org/mockitousage/examples/junitrunner package);
Read more here: MockitoAnnotations
stub(mock.someMethod("some arg"))
.toThrow(new RuntimeException())
.toReturn("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"));
| Method Summary | ||
|---|---|---|
static VerificationMode |
atLeastOnce()
Allows at-least-once verification. |
|
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 VerificationMode |
never()
Alias to times(0), see times(int) |
|
static
|
stub(T methodCall)
Stubs with return value or exception. |
|
static
|
stubVoid(T mock)
Stubs void method with an exception. |
|
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)
Throws an AssertionError if any of given mocks has any unverified interaction. |
|
static void |
verifyZeroInteractions(java.lang.Object... mocks)
Verifies that no interactions happened on given mocks. |
|
| 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, 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 |
| 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> OngoingStubbing<T> stub(T methodCall)
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 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: stubVoid(T)
Stubbing can be overridden: for example common stubbing can go to fixture setup but test methods can override it.
Once stubbed, mocked 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's possible to verify stubbed methods, bear in mind that are verified for free.
See examples in javadoc for Mockito class
methodCall - method call
public 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");
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, atLeastOnce()).someMethod("was called at least once");
//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.
Usually it's not necessary to call verifyNoMoreInteractions() all the time.
See also never() - it is more explicit and communicates an intent well.
Stubbed invocations (if called) are also treated as interactions.
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);Instead of verifyZeroInteractions() you can call verifyNoMoreInteractions() but the first one is more explicit and can read better.
See examples in javadoc for Mockito class
mocks - to be verifiedpublic static <T> VoidMethodStubbable<T> stubVoid(T mock)
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. stub(mock) .toThrow(new RuntimeException()) .toReturn() .on().someMethod();See examples in javadoc for
Mockito class
mock - to stub
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 relevant for in-order verification.
See examples in javadoc for Mockito class
mocks - to be verified in order
public static VerificationMode atLeastOnce()
verify(mock, atLeastOnce()).someMethod("some arg");
See examples in javadoc for Mockito class
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
verify(mock, never()).someMethod();
See examples in javadoc for Mockito class
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||