Mock method with generic type def

721 views
Skip to first unread message

David Selvaraj

unread,
Apr 26, 2012, 4:39:50 PM4/26/12
to mockito
I have a method that converts jason string to a list. The signature
of the method is
public static <T> List<T> mapJsonToObjectList(T typeDef, String json,
Class<?> clazz)

I trying to simulate an exception scenario by throwing an exception
then this method is called and using Mockito to mock this method call
by saying
when(MapUtils.mapJsonToObjectList(Mockito.any(),anyString(),Mockito.any(Class.class))).thenThrow((new
Exception ()));

I am getting an exception
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new
RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with
methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/
hashCode().

Can someone please let me know how to stub this method?

Thanks,
David

Eric Lefevre-Ardant

unread,
Apr 27, 2012, 4:48:05 AM4/27/12
to moc...@googlegroups.com
You are trying to change the behavior of a static method. Mockito can only change the behavior of an instance method (because it creates a special instance, or at the minimum wraps your existing instance into another).

I'd recommend wrapping the call to the static method into an instance method. Then it would be easy to mock/spy/override it.
Personally, I tend to create dependency classes just for that purpose (for example, I often have a SystemManager that mimics some methods from System into instance methods).



--
You received this message because you are subscribed to the Google Groups "mockito" group.
To post to this group, send email to moc...@googlegroups.com.
To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mockito?hl=en.


Reply all
Reply to author
Forward
0 new messages