How to mock generic method in Java with Mockito?

前端 未结 3 2261
生来不讨喜
生来不讨喜 2021-02-15 17:09

How can we mock the IRouteHandlerRegistry? The error is Cannot resolve method thenReturn(IHandleRoute)

public interfac         


        
相关标签:
3条回答
  • 2021-02-15 17:37

    If you write like this it will be ok:

    Mockito.doReturn(handler).when(registry).getHandlerFor(Mockito.any(route.class))
    
    0 讨论(0)
  • 2021-02-15 17:50

    Mockito.when argument should be a method not a mock.

    The correct statement is: when(registry.getHandlerFor (route)).thenReturn(handler)

    0 讨论(0)
  • 2021-02-15 17:52

    Even though TestRoute is a subtype of RouteDefinition, a IHandleRoute<TestRoute> is not a subtype of IHandleRoute<RouteDefinition>.

    The when method from Mockito returns an object of type OngoingStubbing<IHandleRoute<RouteDefinition>>. This is due to the compiler inferring the type parameter TRoute from the method

    <TRoute extends RouteDefinition> IHandleRoute<TRoute> getHandlerFor(TRoute route);
    

    to be RouteDefinition since the argument passed to getHandlerFor is declared of type RouteDefinition.

    On the other hand, the thenReturn method is given an argument of type IHandleRoute<TestRoute> whereas it expects an IHandleRoute<RouteDefinition>, that is the type argument of the OngoingStubbing mentioned earlier. Hence the compiler error.

    To solve this, the simplest way is probably to change the declaration type of route to be TestRoute:

    TestRoute route = new TestRoute();
    
    IRouteHandlerRegistry registry = mock(IRouteHandlerRegistry.class);
    IHandleRoute<TestRoute> handler = mock(IHandleRoute.class);
    
    when(registry.getHandlerFor(route)).thenReturn(handler);
    
    0 讨论(0)
提交回复
热议问题