|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES All Classes | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
org.mockito
Class Mockito
java.lang.Object
org.mockito.Matchers
org.mockito.Mockito
- Direct Known Subclasses:
- BDDMockito
public class Mockito extends Matchers
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.
Contents
1. Let's verify some behaviour!
2. How about some stubbing?
3. Argument matchers
4. Verifying exact number of invocations / at least once / never
5. Stubbing void methods with exceptions
6. Verification in order
7. Making sure interaction(s) never happened on mock
8. Finding redundant invocations
9. Shorthand for mocks creation - @Mock annotation
10. Stubbing consecutive calls (iterator-style stubbing)
11. Stubbing with callbacks
12. doThrow()|doAnswer()|doNothing()|doReturn() family of methods mostly for stubbing voids
13. Spying on real objects
14. Changing default return values of unstubbed invocations (Since 1.7)
15. Capturing arguments for further assertions (Since 1.8.0)
16. Real partial mocks (Since 1.8.0)
17. Resetting mocks (Since 1.8.0)
18. Troubleshooting & validating framework usage (Since 1.8.0)
19. Aliases for behavior driven development (Since 1.8.0)
20. Serializable mocks (Since 1.8.1)
21. New annotations: @Captor, @Spy, @InjectMocks (Since 1.8.3)
22. (**New**) Verification with timeout (Since 1.8.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'.
1. Let's verify some behaviour!
//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.
2. How about some stubbing?
//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);
- By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, ... for int/Integer, boolean/Boolean, ...).
- Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that 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.
3. Argument matchers
Mockito verifies argument values in natural java style: by using an equals() method. Sometimes, when extra flexibility is required then you might use argument matchers:
//stubbing using built-in anyInt() argument matcher when(mockedList.get(anyInt())).thenReturn("element"); //stubbing using 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.
For information solely on custom argument matchers check out javadoc for 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 ArgumentCaptor
class. 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.
4. Verifying exact number of invocations / at least x / never
//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.
5. Stubbing void methods with exceptions
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.
6. Verification in 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");
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.
7. Making sure interaction(s) never happened on mock
//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);
8. Finding redundant invocations
//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 never()
- it is more explicit and communicates the intent well.
9. Shorthand for mocks creation - @Mock annotation
- Minimizes repetitive mock creation code.
- Makes the test class more readable.
- Makes the verification error easier to read because the field name is used to identify the mock.
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: MockitoJUnitRunner
.
Read more here: MockitoAnnotations
10. Stubbing consecutive calls (iterator-style stubbing)
Sometimes we need to stub with different return value/exception for the same method call. Typical use case could be mocking iterators. Original version of Mockito did not have this feature to promote simple mocking. For example, instead of iterators one could use 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"));
Alternative, shorter version of consecutive stubbing:
when(mock.someMethod("some arg")) .thenReturn("one", "two", "three");
11. Stubbing with callbacks
Allows stubbing with generic Answer
interface.
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"));
12. doThrow()|doAnswer()|doNothing()|doReturn() family of methods for stubbing voids (mostly)
Stubbing voids requires different approach from 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:
13. Spying on real objects
You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).
Real spies should be used carefully and occasionally, for example when dealing with legacy code.
Spying on real objects can be associated with "partial mocking" concept. Before the release 1.8, Mockito spies were not real partial mocks. The reason was we thought partial mock is a code smell. At some point we found legitimate use cases for partial mocks (3rd party interfaces, interim refactoring of legacy code, 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");
Important gotcha on spying real objects!
1. Sometimes it's impossible to use 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);
2. Watch out for final methods. Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble. What will happen is the real method will be called *on mock* but *not on the real instance* you passed to the spy() method. Typically you may get a NullPointerException because mock instances don't have fields initiated.
14. Changing default return values of unstubbed invocations (Since 1.7)
You can create a mock with 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 for working with legacy systems .
It is the default answer so it will be used only when you don't stub the method call.
Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS); Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
Read more about this interesting implementation of Answer: RETURNS_SMART_NULLS
15. Capturing arguments for further assertions (Since 1.8.0)
Mockito verifies argument values in natural java style: by using an equals() method. This is also the recommended way of matching arguments because it makes tests clean & 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 ArgumentMatcher
class). Both techniques can be used for making sure certain arguments where passed to mocks. However, ArgumentCaptor may be a better fit if:
- custom argument matcher is not likely to be reused
- you just need it to assert on argument values to complete verification
Custom argument matchers via ArgumentMatcher
are usually better for stubbing.
16. Real partial mocks (Since 1.8.0)
Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks - more reading: here
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 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.
17. Resetting mocks (Since 1.8.0)
Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. Normally, you don't need to reset your mocks, just create new mocks for each test method.
Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified tests. First potential code smell is reset() in the middle of the test method. This probably means you're testing too much. Follow the whisper of your test methods: "Please keep us small & 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
18. Troubleshooting & validating framework usage (Since 1.8.0)
First of all, in case of any trouble, I encourage you to read the Mockito FAQ: http://code.google.com/p/mockito/wiki/FAQ
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 validateMockitoUsage()
19. Aliases for behavior driven development (Since 1.8.0)
Behavior Driven Development style of writing tests uses //given //when //then comments as fundamental parts of your test methods. This is exactly how we write our tests and we warmly encourage you to do so!
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 BDDMockito
class introduces an alias so that you stub method calls with 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()); }
20. (**New**) Serializable mocks (Since 1.8.1)
Mocks can be made serializable. With this feature you can use a mock in a place that requires dependencies to be serializable.
WARNING: This should be rarely used in unit testing.
The behaviour was implemented for a specific use case of a BDD spec that had an unreliable external dependency. This was in a web environment and the objects from the external dependency were being serialized to pass between layers.
To create serializable mock use 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());
21. (**New**) New annotations: @Captor, @Spy, @InjectMocks (Since 1.8.3)
Release 1.8.3 brings new annotations that may be helpful on occasion:
- @
Captor
simplifies creation ofArgumentCaptor
- useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings - @
Spy
- you can use it insteadspy(Object)
. - @
InjectMocks
- injects mocks into tested object automatically.
All new annotations are *only* processed on MockitoAnnotations.initMocks(Object)
22. (**New**) Verification with timeout (Since 1.8.5)
Allows verifying with timeout. 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 lest* 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();
Field Summary | |
---|---|
static Answer<java.lang.Object> |
CALLS_REAL_METHODS Optional Answer to be used with mock(Class, Answer) |
static Answer<java.lang.Object> |
RETURNS_DEEP_STUBS Optional Answer to be used with mock(Class, Answer) |
static Answer<java.lang.Object> |
RETURNS_DEFAULTS The default Answer of every mock if the mock was not stubbed. |
static Answer<java.lang.Object> |
RETURNS_MOCKS Optional Answer to be used with mock(Class, Answer) |
static Answer<java.lang.Object> |
RETURNS_SMART_NULLS Optional Answer to be used with mock(Class, Answer) |
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 |
doCallRealMethod() Use doCallRealMethod() when you want to call the real implementation of a method. |
|
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, Answer defaultAnswer) Creates mock with a specified strategy for its answers to interactions. |
|
static
|
mock(java.lang.Class<T> classToMock, MockSettings mockSettings) Creates a mock with some non-standard settings. |
|
static
|
mock(java.lang.Class<T> classToMock, ReturnValues returnValues) Deprecated. Please use mock(Foo.class, defaultAnswer); 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. Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS); Foo mockTwo = mock(Foo.class, new YourOwnReturnValues()); See examples in javadoc for |
|
static
|
mock(java.lang.Class<T> classToMock, java.lang.String name) Specifies mock name. |
|
static VerificationMode |
never() Alias to times(0), see times(int) |
|
static VerificationMode |
only() Allows checking if given method was the only one invoked. |
|
static
|
reset(T... mocks) Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. |
|
static
|
spy(T object) Creates a spy of the real object. |
|
static
|
stub(T methodCall) Stubs a method call with return value or an exception. |
|
static
|
stubVoid(T mock) Deprecated. Use doThrow(Throwable) method for stubbing voids |
|
static VerificationWithTimeout |
timeout(int millis) Allows verifying with timeout. |
|
static VerificationMode |
times(int wantedNumberOfInvocations) Allows verifying exact number of invocations. |
|
static void |
validateMockitoUsage() First of all, in case of any trouble, I encourage you to read the Mockito FAQ: http://code.google.com/p/mockito/wiki/FAQ |
|
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. |
|
static MockSettings |
withSettings() Allows mock creation with additional mock settings. |
Methods inherited from class org.mockito.Matchers |
---|
any, any, anyBoolean, anyByte, anyChar, anyCollection, anyCollectionOf, anyDouble, anyFloat, anyInt, anyList, anyListOf, anyLong, anyMap, anyObject, anySet, anySetOf,anyShort, anyString, anyVararg, 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 |
Field Detail |
---|
RETURNS_DEFAULTS
public static final Answer<java.lang.Object> RETURNS_DEFAULTS
- The default Answer of every mock if the mock was not stubbed. Typically it just returns some empty value.
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
ReturnsEmptyValues
(returns zeros, empty collections, nulls, etc.)
RETURNS_SMART_NULLS
public static final Answer<java.lang.Object> RETURNS_SMART_NULLS
- Optional Answer to be used with
mock(Class, Answer)
Answer
can be used to define the return values of unstubbed invocations.This implementation can be helpful when working with legacy code. Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException. This implementation of Answer returns SmartNull instead of null. SmartNull gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.
ReturnsSmartNulls first tries to return ordinary return values (see
ReturnsMoreEmptyValues
) then it tries to return SmartNull. If the return type is final then plain null is returned.ReturnsSmartNulls will be probably the default return values strategy in Mockito 2.0
Example:
Foo mock = (Foo.class, RETURNS_SMART_NULLS); //calling unstubbed method here: Stuff stuff = mock.getStuff(); //using object returned by unstubbed call: stuff.doSomething(); //Above doesn't yield NullPointerException this time! //Instead, SmartNullPointerException is thrown. //Exception's cause links to unstubbed mock.getStuff() - just click on the stack trace.
RETURNS_MOCKS
public static final Answer<java.lang.Object> RETURNS_MOCKS
- Optional Answer to be used with
mock(Class, Answer)
Answer
can be used to define the return values of unstubbed invocations.This implementation can be helpful when working with legacy code.
ReturnsMocks first tries to return ordinary return values (see
ReturnsMoreEmptyValues
) then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain null is returned.
RETURNS_DEEP_STUBS
public static final Answer<java.lang.Object> RETURNS_DEEP_STUBS
- Optional Answer to be used with
mock(Class, Answer)
Example that shows how deep stub works:
Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS); // note that we're stubbing a chain of methods here: getBar().getName() when(mock.getBar().getName()).thenReturn("deep"); // note that we're chaining method calls: getBar().getName() assertEquals("deep", mock.getBar().getName());
Verification API does not support 'chaining' so deep stub doesn't change how you do verification.WARNING: This feature should rarely be required for regular clean code! Leave it for legacy code. Mocking a mock to return a mock, to return a mock, (...), to return something meaningful hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).
Good quote I've seen one day on the web: every time a mock returns a mock a fairy dies.
How deep stub work internally?
//this: Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS); when(mock.getBar().getName(), "deep"); //is equivalent of Foo foo = mock(Foo.class); Bar bar = mock(Bar.class); when(foo.getBar()).thenReturn(bar); when(bar.getName()).thenReturn("deep");
This feature will not work when any return type of methods included in the chain cannot be mocked (for example: is a primitive or a final class). This is because of java type system.
CALLS_REAL_METHODS
public static final Answer<java.lang.Object> CALLS_REAL_METHODS
- Optional Answer to be used with
mock(Class, Answer)
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();
Constructor Detail |
---|
Mockito
public Mockito()
Method Detail |
---|
mock
public static <T> T mock(java.lang.Class<T> classToMock)
- Creates mock object of given class or interface.
See examples in javadoc for
Mockito
class - Parameters:
classToMock
- class or interface to mock- Returns:
- mock object
mock
public static <T> T mock(java.lang.Class<T> classToMock, java.lang.String name)
- Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.
Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators. If you have too many mocks then refactor the code so that it's easy to test/debug without necessity of naming mocks.
If you use @Mock annotation then you've got naming mocks for free! @Mock uses field name as mock name.
Read more.
See examples in javadoc for
Mockito
class - Parameters:
classToMock
- class or interface to mockname
- of the mock- Returns:
- mock object
mock
@Deprecated public static <T> T mock(java.lang.Class<T> classToMock, ReturnValues returnValues)
- Deprecated. Please use mock(Foo.class, defaultAnswer);
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.
Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS); Foo mockTwo = mock(Foo.class, new YourOwnReturnValues());
See examples in javadoc for
Mockito
class - Parameters:
classToMock
- class or interface to mockreturnValues
- default return values for unstubbed methods- Returns:
- mock object
mock
public static <T> T mock(java.lang.Class<T> classToMock, Answer defaultAnswer)
- Creates mock with a specified strategy for its answers to interactions. 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.
It is the default answer so it will be used only when you don't stub the method call.
Foo mock = mock(Foo.class, RETURNS_SMART_NULLS); Foo mockTwo = mock(Foo.class, new YourOwnAnswer());
See examples in javadoc for
Mockito
class - Parameters:
classToMock
- class or interface to mockdefaultAnswer
- default answer for unstubbed methods- Returns:
- mock object
mock
public static <T> T mock(java.lang.Class<T> classToMock, MockSettings mockSettings)
- Creates a mock with some non-standard settings.
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
MockSettings
.Listener mock = mock(Listener.class, withSettings() .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); );
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?See also
withSettings()
See examples in javadoc for
Mockito
class - Parameters:
classToMock
- class or interface to mockmockSettings
- additional mock settings- Returns:
- mock object
spy
public static <T> T spy(T object)
- Creates a spy of the real object. The spy calls real methods unless they are stubbed.
Real spies should be used carefully and occasionally, for example when dealing with legacy code.
As usual you are going to read the partial mock warning: Object oriented programming 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:
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!
1. Sometimes it's impossible to usewhen(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);
2. Watch out for final methods. Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble. What will happen is the real method will be called *on mock* but *not on the real instance* you passed to the spy() method. Typically you may get a NullPointerException because mock instances don't have fields initiated.See examples in javadoc for
Mockito
class - Parameters:
object
- to spy on- Returns:
- a spy of the real object
stub
public static <T> DeprecatedOngoingStubbing<T> stub(T methodCall)
- Stubs a method call with return value or an exception. E.g:
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");
Some users find stub() confusing therefore
when(Object)
is recommended over stub()//Instead of: stub(mock.count()).toReturn(10); //You can do: when(mock.count()).thenReturn(10);
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. 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.
- Parameters:
methodCall
- method call- Returns:
- DeprecatedOngoingStubbing object to set stubbed value/exception
when
public static <T> OngoingStubbing<T> when(T methodCall)
- Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.
Simply put: "When the x method is called then return y".
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"); //Alternative, shorter version for consecutive stubbing: when(mock.someMethod("some arg")) .thenReturn("one", "two"); //is the same as: when(mock.someMethod("some arg")) .thenReturn("one") .thenReturn("two"); //shorter version for consecutive method calls throwing exceptions: when(mock.someMethod("some arg")) .thenThrow(new RuntimeException(), new NullPointerException();
For stubbing void methods with throwables see:doThrow(Throwable)
Stubbing can be overridden: for example common stubbing can go to fixture setup but the test methods can override it. Please note that 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.
See examples in javadoc for
Mockito
class - Parameters:
methodCall
- method to be stubbed
verify
public static <T> T verify(T mock)
- Verifies certain behavior happened once
Alias to
verify(mock, times(1))
E.g:verify(mock).someMethod("some arg");
Above is equivalent to:verify(mock, times(1)).someMethod("some arg");
Arguments passed are compared using equals() method. Read about
ArgumentCaptor
orArgumentMatcher
to find out other ways of matching / asserting arguments passed.Although it is possible to verify a stubbed invocation, usually it's just redundant. Let's say you've stubbed foo.bar(). If your code cares what foo.bar() returns then something else breaks(often before even verify() gets executed). If your code doesn't care what get(0) returns then it should not be stubbed. Not convinced? See here.
See examples in javadoc for
Mockito
class - Parameters:
mock
- to be verified- Returns:
- mock object itself
verify
public static <T> T verify(T mock, VerificationMode mode)
- Verifies certain behavior happened at least once / exact number of times / never. E.g:
verify(mock, times(5)).someMethod("was called five times"); verify(mock, atLeast(2)).someMethod("was called at least two times"); //you can use flexible argument matchers, e.g: verify(mock, atLeastOnce()).someMethod(anyString());
times(1) is the default and can be omittedArguments passed are compared using equals() method. Read about
ArgumentCaptor
orArgumentMatcher
to find out other ways of matching / asserting arguments passed. - Parameters:
mock
- to be verifiedmode
- times(x), atLeastOnce() or never()- Returns:
- mock object itself
reset
public static <T> void reset(T... mocks)
- Smart Mockito users hardly use this feature because they know it could be a sign of poor tests. Normally, you don't need to reset your mocks, just create new mocks for each test method.
Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified tests. First potential code smell 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
- Type Parameters:
T
-- Parameters:
mocks
- to be reset
verifyNoMoreInteractions
public static void verifyNoMoreInteractions(java.lang.Object... mocks)
- Checks if any of given mocks has any unverified interaction.
You can use this method after you verified your mocks - to make sure that nothing else was invoked on your mocks.
See also
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 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.
This method will also detect unverified invocations that occurred before the test method, for example: in setUp(), @Before method or in constructor. Consider writing nice code that makes interactions only in test methods.
Example:
//interactions mock.doSomething(); mock.doSomethingUnexpected(); //verification verify(mock).doSomething(); //following will fail because 'doSomethingUnexpected()' is unexpected verifyNoMoreInteractions(mock);
See examples in javadoc forMockito
class - Parameters:
mocks
- to be verified
verifyZeroInteractions
public static void verifyZeroInteractions(java.lang.Object... mocks)
- Verifies that no interactions happened on given mocks.
verifyZeroInteractions(mockOne, mockTwo);
This method will also detect invocations that occurred before the test method, for example: in setUp(), @Before method or in constructor. Consider writing nice code that makes interactions only in test methods.See also
never()
- it is more explicit and communicates the intent well.See examples in javadoc for
Mockito
class - Parameters:
mocks
- to be verified
stubVoid
public static <T> VoidMethodStubbable<T> stubVoid(T mock)
- Deprecated. Use
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 forMockito
class - Parameters:
mock
- to stub- Returns:
- stubbable object that allows stubbing with throwable
doThrow
public static Stubber doThrow(java.lang.Throwable toBeThrown)
- Use doThrow() when you want to stub the void method with an exception.
Stubbing voids requires different approach from
when(Object)
because the compiler does not like void methods inside brackets...Example:
doThrow(new RuntimeException()).when(mock).someVoidMethod();
- Parameters:
toBeThrown
- to be thrown when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
doCallRealMethod
public static Stubber doCallRealMethod()
- Use doCallRealMethod() when you want to call the real implementation of a method.
As usual you are going to read the partial mock warning: Object oriented programming is more 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
spy(Object)
to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.Example:
Foo mock = mock(Foo.class); doCallRealMethod().when(mock).someVoidMethod(); // this will call the real implementation of Foo.someVoidMethod() mock.someVoidMethod();
See examples in javadoc for
Mockito
class - Returns:
- stubber - to select a method for stubbing
doAnswer
public static Stubber doAnswer(Answer answer)
- Use doAnswer() when you want to stub a void method with generic
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();
See examples in javadoc for
Mockito
class - Parameters:
answer
- to answer when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
doNothing
public static Stubber doNothing()
- Use doNothing() for setting void methods to do nothing. Beware that void methods on mocks do nothing by default! However, there are rare situations when doNothing() comes handy:
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();
See examples in javadoc for
Mockito
class - Returns:
- stubber - to select a method for stubbing
doReturn
public static Stubber doReturn(java.lang.Object toBeReturned)
- Use doReturn() in those rare occasions when you cannot use
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. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.See examples in javadoc for
Mockito
class - Parameters:
toBeReturned
- to be returned when the stubbed method is called- Returns:
- stubber - to select a method for stubbing
inOrder
public static InOrder inOrder(java.lang.Object... mocks)
- Creates InOrder object that allows verifying mocks in order.
InOrder inOrder = inOrder(firstMock, secondMock); inOrder.verify(firstMock).add("was called first"); inOrder.verify(secondMock).add("was called second");
Verification in order is flexible - you don't have to verify all interactions one-by-one but only those that you are interested in testing in order.Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
InOrder verification is 'greedy'. You will hardly every notice it but if you want to find out more search for 'greedy' on the Mockito wiki pages.
As of Mockito 1.8.4 you can verifyNoMoreInvocations() in order-sensitive way. Read more:
InOrder.verifyNoMoreInteractions()
See examples in javadoc for
Mockito
class - Parameters:
mocks
- to be verified in order- Returns:
- InOrder object to be used to verify in order
times
public static VerificationMode times(int wantedNumberOfInvocations)
- Allows verifying exact number of invocations. E.g:
verify(mock, times(2)).someMethod("some arg");
See examples in javadoc forMockito
class - Parameters:
wantedNumberOfInvocations
- wanted number of invocations- Returns:
- verification mode
never
public static VerificationMode never()
- Alias to times(0), see
times(int)
Verifies that interaction did not happen. E.g:
verify(mock, never()).someMethod();
If you want to verify there were NO interactions with the mock check out
verifyZeroInteractions(Object...)
orverifyNoMoreInteractions(Object...)
See examples in javadoc for
Mockito
class - Returns:
- verification mode
atLeastOnce
public static VerificationMode atLeastOnce()
- Allows at-least-once verification. E.g:
verify(mock, atLeastOnce()).someMethod("some arg");
Alias to atLeast(1)See examples in javadoc for
Mockito
class - Returns:
- verification mode
atLeast
public static VerificationMode atLeast(int minNumberOfInvocations)
- Allows at-least-x verification. E.g:
verify(mock, atLeast(3)).someMethod("some arg");
See examples in javadoc forMockito
class - Parameters:
minNumberOfInvocations
- minimum number of invocations- Returns:
- verification mode
atMost
public static VerificationMode atMost(int maxNumberOfInvocations)
- Allows at-most-x verification. E.g:
verify(mock, atMost(3)).someMethod("some arg");
See examples in javadoc forMockito
class - Parameters:
maxNumberOfInvocations
- max number of invocations- Returns:
- verification mode
only
public static VerificationMode only()
- Allows checking if given method was the only one invoked. E.g:
verify(mock, only()).someMethod(); //above is a shorthand for following 2 lines of code: verify(mock).someMethod(); verifyNoMoreInvocations(mock);
See also
verifyNoMoreInteractions(Object...)
See examples in javadoc for
Mockito
class - Returns:
- verification mode
timeout
public static VerificationWithTimeout timeout(int millis)
- Allows verifying with timeout. 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.
//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 lest* 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();
See examples in javadoc forMockito
class - Parameters:
millis
- - time span in millis- Returns:
- verification mode
validateMockitoUsage
public static void validateMockitoUsage()
- First of all, in case of any trouble, I encourage you to read the Mockito FAQ: http://code.google.com/p/mockito/wiki/FAQ
In case of questions you may also post to mockito mailing list: http://groups.google.com/group/mockito
validateMockitoUsage() explicitly validates the framework state to detect invalid use of Mockito. However, this feature is optional because Mockito validates the usage all the time... but there is a gotcha so read on.
Examples of incorrect use:
//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);
Mockito throws exceptions if you misuse it so that you know if your tests are written correctly. The gotcha is that Mockito does the validation next time you use the framework (e.g. next time you verify, stub, call mock etc.). But even though the exception might be thrown in the next test, the exception message contains a navigable stack trace element with location of the defect. Hence you can click and find the place where Mockito was misused.Sometimes though, you might want to validate the framework usage explicitly. For example, one of the users wanted to put validateMockitoUsage() in his @After method so that he knows immediately when he misused Mockito. Without it, he would have known about it not sooner than next time he used the framework. One more benefit of having validateMockitoUsage() in @After is that jUnit runner 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.
Built-in runner:
MockitoJUnitRunner
does validateMockitoUsage() after each test method.Bear in mind that usually you don't have to validateMockitoUsage() and framework validation triggered on next-time basis should be just enough, mainly because of enhanced exception message with clickable location of defect. However, I would recommend validateMockitoUsage() if you already have sufficient test infrastructure (like your own runner or base class for all tests) because adding a special action to @After has zero cost.
See examples in javadoc for
Mockito
class
withSettings
public static MockSettings withSettings()
- Allows mock creation with additional mock settings.
Don't use it too often. Consider writing simple tests that use simple mocks. Repeat after me: simple tests push simple, KISSy, readable & maintainable code. If you cannot write a test in a simple way - refactor the code under test.
Examples of mock settings:
//Creates mock with different default answer & 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));
MockSettings
has been introduced for two reasons. Firstly, to make it easy to add another mock settings when the demand comes. Secondly, to enable combining different mock settings without introducing zillions of overloaded mock() methods.See javadoc for
MockSettings
to learn about possible mock settings. - Returns:
- mock settings instance with defaults.
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES All Classes | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |