lrx*_*rxw 145 java generics mockito
是否可以通过泛型传递接口的类型?
界面:
public interface AsyncCallback<T>
Run Code Online (Sandbox Code Playgroud)
在我的测试方法中:
Mockito.any(AsyncCallback.class)
Run Code Online (Sandbox Code Playgroud)
把<ResponseX>
后面或.class
没有工作.
thS*_*oft 258
有一种类型安全的方法:使用ArgumentMatchers.any()
和限定类型:
ArgumentMatchers.<AsyncCallback<ResponseX>>any()
Run Code Online (Sandbox Code Playgroud)
正如pierrefevrier在评论中提到的那样,Mockito的新版本就是这样
ArgumentMatchers.<AsyncCallback<ResponseX>>any()
Run Code Online (Sandbox Code Playgroud)
her*_*man 58
使用Java 8,您可以简单地使用any()
(假设静态导入)而不使用参数或类型参数,因为增强的类型推断.编译器现在知道您实际意味着的目标类型(方法参数的类型)Matchers.<AsyncCallback<ResponseX>>any()
,这是Java 8之前的解决方案.
the*_*toy 14
我不得不采用以下机制来允许泛型:
import static org.mockito.Matchers.any;
List<String> list = any();
when(callMyMethod.getResult(list)).thenReturn(myResultString);
Run Code Online (Sandbox Code Playgroud)
希望这有助于某人.
发布 pierrefevrier 评论作为答案,如果它出现在答案中而不是评论中,这可能会很有用。
使用新版本的 Mockito: (Matchers.<AsyncCallback<ResponseX>>any()