如何使用Mockito模拟Java中的泛型方法? [英] How to mock generic method in Java with Mockito?

查看:135
本文介绍了如何使用Mockito模拟Java中的泛型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何模拟 IRouteHandlerRegistry ?错误是无法解析方法thenReturn(IHandleRoute< TestRoute>)

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

推荐答案

即使 TestRoute RouteDefinition 的子类型,也是 IHandleRoute< TestRoute> 不是不是 IHandleRoute< RouteDefinition> 的子类型.

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

Mockito的 when 方法返回类型为 OngoingStubbing< IHandleRoute< RouteDefinition>>> 的对象.这是由于编译器从方法中推断出类型参数 TRoute

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

成为 RouteDefinition ,因为传递给 getHandlerFor 的参数声明为 RouteDefinition 类型.

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

另一方面,给 thenReturn 方法赋予类型为 IHandleRoute< TestRoute> 的参数,而它期望的是 IHandleRoute< RouteDefinition> ,这是前面提到的 OngoingStubbing 的类型参数.因此出现了编译器错误.

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.

要解决此问题,最简单的方法可能是将 route 的声明类型更改为 TestRoute :

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

这篇关于如何使用Mockito模拟Java中的泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆