Mockito匹配器将方法与泛型和供应商进行匹配

Mar*_*lon 5 java generics unit-testing matcher mockito

我正在使用Java 1.8.0_131,Mockito 2.8.47和PowerMock 1.7.0。我的问题与PowerMock无关,它已发布给Mockito.when(…)匹配器。

我需要一种模拟此方法的解决方案,该方法由我的受测类调用:

public static <T extends Serializable> PersistenceController<T> createController(
    final Class<? extends Serializable> clazz,
    final Supplier<T> constructor) { … }
Run Code Online (Sandbox Code Playgroud)

从被测类中调用该方法,如下所示:

PersistenceController<EventRepository> eventController =
    PersistenceManager.createController(Event.class, EventRepository::new);
Run Code Online (Sandbox Code Playgroud)

为了进行测试,我首先创建了我的模拟对象,该对象应在调用上述方法时返回:

final PersistenceController<EventRepository> controllerMock =
    mock(PersistenceController.class);
Run Code Online (Sandbox Code Playgroud)

那很简单。问题在于方法参数的匹配器,因为该方法将泛型与供应商结合使用作为参数。以下代码按预期编译并返回null:

when(PersistenceManager.createController(any(), any()))
    .thenReturn(null);
Run Code Online (Sandbox Code Playgroud)

当然,我不想返回null。我想返回我的模拟对象。由于泛型,因此无法编译。为了符合类型,我必须编写如下内容:

when(PersistenceManager.createController(Event.class, EventRepository::new))
    .thenReturn(controllerMock);
Run Code Online (Sandbox Code Playgroud)

这样可以编译,但是my中的参数不是匹配器,因此匹配不起作用,并且返回null。我不知道如何编写一个匹配器来匹配我的参数并返回我的模拟对象。你有什么主意吗?

非常感谢Marcus

Sto*_*ica 6

问题在于,编译器无法推断any()第二个参数的类型。您可以使用以下Matcher.<...>any()语法指定它:

when(PersistenceManager.createController(
    any(), Matchers.<Supplier<EventRepository>>any())
).thenReturn(controllerMock);
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Mockito 2(Matchers不推荐使用),请ArgumentMatchers改用:

when(PersistenceManager.createController(
    any(), ArgumentMatchers.<Supplier<EventRepository>>any())
).thenReturn(controllerMock);
Run Code Online (Sandbox Code Playgroud)