Alex Rivera | Logout

Mockito isA(Class<T> clazz) How to resolve type safety?

Asked 2012-08-17T19:46:30.073
33

in my test I have the following line:

when(client.runTask(anyString(), anyString(), isA(Iterable.class)).thenReturn(...)

isA(Iterable.class) produces warning that it needs unchecked conversion to conform to Iterable<Integer> . What is syntax for that?

isA(Iterable<Integer>.class)
isA((Iterable<Integer>)Iterable.class

do not work.

Any suggestions?

Edit
Report

1 Answer

2

There is no way to do this. To simplify, you can't initialize this variable without warning :

Class<Iterable<Integer>> iterableIntegerClass = ?

One solution might be to use the pseudo-typedef antipattern, ,you create and use an IntegerIterable interface

interface IntegerIterable extends Iterable<Integer> {}

then

isA(IntegerIterable.class)

will no more produce warning. But you will have to extend the class implementing Iterable to let them implements IntegerIterable :) For example :

public class IntegerArrayList extends ArrayList<Integer> implements IntegerIterable {}

Mmm tasty...

So, i will sugest you to consider to just paper over the cracks by adding to your method :

@SuppressWarnings("unchecked")
answered 2012-08-17T21:09:05.233

Your Answer