开发者

Specify the class of a generic interface to mock

I'm trying to cap开发者_运维知识库ture an argument using Mockito. This argument is of type List< MyClass >. But I can't find the proper syntax to specify it.

I can do this:

ArgumentCaptor< MyClass > captor = 
   ArgumentCaptor.forClass( MyClass.class );

But I don't get this to compile:

ArgumentCaptor< List<MyClass> > captor = 
   ArgumentCaptor.forClass( List<MyClass>.class );

Is there a way?


It should work using the @Captor annotation:

@Captor
    private ArgumentCaptor<ArrayList<SomeType>> captor;


Unfortunately no, .class will only return the Class<List> object, where List is a rawtype. The implementation isn't perfect, and nested type information can't be obtained using .class. Something like List<Foo>.class is invalid syntax because no such Class<List<Foo>> object exists anywhere.


I think this is because Java doesn't determine the type of a parametreized class statically.

The same way this does not compile:

Class<?> c1 = ArrayList<String>.class; 

And this neither as on top of the type resolution issue List is an interface:

Class<?> c2 = List<String>.class; 

But this does compile, and you can probably do something similar:

public class MyList implements List<String> {
    ... the List's methods to implement ...
}

// and later in the code:

Class<?> c3 = MyList.class;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜