How to mock generic method in Java with Mockito?

你说的曾经没有我的故事 提交于 2021-01-21 04:18:44

问题


How can we mock the IRouteHandlerRegistry? The error is 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);
}

回答1:


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);



回答2:


If you write like this it will be ok:

Mockito.doReturn(handler).when(registry).getHandlerFor(Mockito.any(route.class))



回答3:


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

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



来源:https://stackoverflow.com/questions/31621342/how-to-mock-generic-method-in-java-with-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!