我们如何模拟 IRouteHandlerRegistry
?错误是 Cannot resolve method thenReturn(IHandleRoute<TestRoute>)
public interface RouteDefinition { }
public class TestRoute implements RouteDefinition { }
public interface IHandleRoute<TRoute extends RouteDefinition> {
Route getHandlerFor(TRoute route);
}
public interface IRouteHandlerRegistry {
<TRoute extends RouteDefinition> IHandleRoute<TRoute> getHandlerFor(TRoute route);
}
@Test
@SuppressWarnings("unchecked")
public void test() {
// in my test
RouteDefinition route = new TestRoute(); // TestRoute implements RouteDefinition
IRouteHandlerRegistry registry = mock(IRouteHandlerRegistry.class);
IHandleRoute<TestRoute> handler = mock(IHandleRoute.class);
// Error: Cannot resolve method 'thenReturn(IHandleRoute<TestRoute>)'
when(registry.getHandlerFor(route)).thenReturn(handler);
}
最佳答案
尽管TestRoute
是 RouteDefinition
的子类型, 一个 IHandleRoute<TestRoute>
不是 IHandleRoute<RouteDefinition>
的子类型.
when
Mockito 的方法返回类型为 OngoingStubbing<IHandleRoute<RouteDefinition>>
的对象.这是由于编译器推断类型参数 TRoute
从方法
<TRoute extends RouteDefinition> IHandleRoute<TRoute> getHandlerFor(TRoute route);
成为 RouteDefinition
因为参数传递给了getHandlerFor
声明类型为 RouteDefinition
.
另一方面,thenReturn
方法被赋予类型为 IHandleRoute<TestRoute>
的参数而它期望一个 IHandleRoute<RouteDefinition>
,这是 OngoingStubbing
的类型参数较早前提过。因此编译器错误。
要解决这个问题,最简单的方法可能是更改 route
的声明类型成为TestRoute
:
TestRoute route = new TestRoute();
IRouteHandlerRegistry registry = mock(IRouteHandlerRegistry.class);
IHandleRoute<TestRoute> handler = mock(IHandleRoute.class);
when(registry.getHandlerFor(route)).thenReturn(handler);
关于java - 如何使用 Mockito 模拟 Java 中的泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31621342/