Mockito mock child classes too…


Recently, I had a requirement to mock out the child classes of a parent mocked class. Typically we reach this kind of situation when we want to mock out a view and its components.

I was able to get a small snipper for solving this problem:

   protected T createMock(Class clazz) {  
     return (T) mock(clazz, createAnswer());  
   }  
   Answer createAnswer() {  
     return new Answer() {  
       public HashMap methodObjectHashMap = new HashMap();  
       @Override  
       public Object answer(InvocationOnMock invocationOnMock) throws Throwable {  
         Method method = invocationOnMock.getMethod();  
         if (method.getReturnType().getName().equalsIgnoreCase(“void”)){  
           return null;  
         }  
         if (methodObjectHashMap.get(method) == null) {  
           methodObjectHashMap.put(method, mock(method.getReturnType()));  
         }  
         return methodObjectHashMap.get(method);  
       }  
     };  
   }  

Instead of using the mockito’s mock method to create a mock object of a class, We can use the creatMock method which will get the required mock object with each properties also as mocked objects.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s