How to simulate a common method in Java using Mockito?

How can we mock IRouteHandlerRegistry? ErrorCannot 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);
}
+4
source share
3 answers

Even if it TestRouteis a subtype RouteDefinition, a IHandleRoute<TestRoute>is not a subtype IHandleRoute<RouteDefinition>.

The method whenfrom Mockito returns an object of type OngoingStubbing<IHandleRoute<RouteDefinition>>. This is because the compiler infers the type parameter TRoutefrom the method

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

will be RouteDefinitionbecause the argument passed in getHandlerForis declared type RouteDefinition.

On the other hand, the method thenReturnreceives a type argument IHandleRoute<TestRoute>, while it expects IHandleRoute<RouteDefinition>, that is, the type argument OngoingStubbingmentioned earlier. Therefore, a compiler error.

, - route TestRoute:

TestRoute route = new TestRoute();

IRouteHandlerRegistry registry = mock(IRouteHandlerRegistry.class);
IHandleRoute<TestRoute> handler = mock(IHandleRoute.class);

when(registry.getHandlerFor(route)).thenReturn(handler);
+3

, :

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

Mockito.when the argument should be a method, not a layout.

Correct statement:  when(registry.getHandlerFor (route)).thenReturn(handler)

+1
source

Source: https://habr.com/ru/post/1599598/


All Articles