Sunday, June 29, 2014

Mockito usage preparation

Mockito is required when:

-    We don't require / unable to create an object to a class which depends on any network related objects.  We can create a mock object to that class and write stubbing method calls.

-    We are unable to stop an object functionality which depends on other object ( returns some response) that will be impossible.  We can spy the real object and write stubbing method calls.

-   


Limitations with Mockito:
-----------------------------------------
-    We can't create mock object to final / immutable classes.
-    We can't write stub method calls for static methods in a class.
-    We can't write stub method calls for private methods in a class.
-    Mockito framework is useful only to create mock object and write stubb method calls on those mocked objects, ( not on static methods ). Go for PowerMockito


Basic examples:

Creating a mock object to class / Interface:
-------------------------------------------------------------------
import org.mockito.Mockito;
    List mockedList=Mockito.mock(List.class);   
    List mockedListC=Mockito.mock(ArrayList.class);



 

Writing basic stub method calls for non-void methods:
---------------------------------------------------------------------------------------
    Mockito.when(mockedList.get(Mockito.anyInt())).thenReturn("mockedresult");

 

Writing basic stub method calls for void methods - mocked object :
----------------------------------------------------------------------------------------------------------
    Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets...

    doThrow(new RuntimeException()).when(mockedList).clear();

 
 Creating spy object:
-------------------------------
When you use the spy then the real methods are called (unless a method was stubbed).
    List list = new LinkedList();
    List spy = spy(list);


Writing basic stub method calls for void methods - spy object:
-----------------------------------------------------------------------------------------------
Sometimes it's impossible or impractical to use when(Object) for stubbing spies. Therefore when using spies please consider doReturn|Answer|Throw() family of methods for stubbing.
    List list = new LinkedList();
    List spy = spy(list);
   
    //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
    when(spy.get(0)).thenReturn("foo");
   
    //You have to use doReturn() for stubbing
    doReturn("foo").when(spy).get(0);

 
Reset mock objects:
--------------------------------
    Mockito.reset(mockedList);






Maven depedency:
       
            org.mockito
            mockito-all
            1.9.5
       

No comments:

Post a Comment