我很难模拟泛型类型。以下是我的班级定义
public interface MyHandler<S, T extends BaseClass> {
void handle(S t1, T t2);
}
下面是我的实现类
public class MyFirstConcreteHandler implements MyHandler<MyClass,OtherClass>{
// implementation
}
这里
OtherClass
延伸BaseClass
下面是我的工厂类
public class MyHandlerFactory {
Map<String, MyHandler<MyClass, ? extends BaseClass>> myHandlers;
public MyHandler<MyClass,? extends BaseClass> getHandler(String key) {
// myhandlers will be populated in constructor
return myHandlers.get(key.toLowerCase());
}
}
以下是我试图嘲笑的内容
MyHandlerFactory myHandlerFactory = mock(MyHandlerFactory.class)
MyFirstConcreteHandler mockHandler = mock(MyFirstConcreteHandler.class);
when(myHandlerFactory.getHandler("random")).thenReturn(mockHandler);
以下是我遇到的编译器错误
Cannot resolve method 'thenReturn(MyFirstConcreteHandler)'
我该如何解决这个问题?
您需要转换为原始类型。
when(myHandlerFactory.getHandler("random")).thenReturn((MyHandler)mockHandler);