Mockito Framework
Mockito Framework
*`
Agenda
Mock? Why?
Mockito ?
Mockito - how to drink it? - framework basics
Mockito and Spring
Mockito drinking examples
Mockito with threads
Mockito - pros and cons
What else to use?
Rules to remember
*`
Mock? Why?
*`
Mock? Why?
*`
Mockito?
is a mocking framework that tastes really good. It lets you write
beautiful tests with clean & simple API. Mockito doesn't give you
hangover because the tests are very readable and they produce
clean verification errors (from code.google.com/p/mockito)
*`
//mock creation
LinkedList mockedList = mock(LinkedList.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.
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.
*`
*`
Verifying verify()
mockedList.add("once");
mockedList.add("twice");
mockedList.add("twice");
//following
//exact
//verification
//verification
using atLeast()/atMost()
verify(mockedList, atLeastOnce()).add("three times");
verify(mockedList, atLeast(2)).add("five times");
verify(mockedList, atMost(5)).add("three times");
verifyZeroInteractions(mockedList2)...
*`
*`
when(mock.someMethod("some arg")).thenReturn("foo");
doReturn("bar").when(mock).foo();
*`
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
doThrow(new RuntimeException()).when(mockedList).clear();
//following throws RuntimeException:
mockedList.clear();
*`
*`
Cons
*`
*`
Thank you!!
Bibliography:
http://docs.mockito.googlecode.com
http://schuchert.wikispaces.com/Mockito.LoginServiceExample
http://www.javablog.eu/java/mockito-testowanie-asynchronicznychwywolan/
*`