Mockito匹配器以匹配具有泛型和供应商的方法 [英] Mockito matcher to match a method with generics and a supplier

查看:126
本文介绍了Mockito匹配器以匹配具有泛型和供应商的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Java 1.8.0_131, Mockito 2.8.47 and PowerMock 1.7.0. My question is not related to PowerMock, it is released to a Mockito.when(…) matcher.

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

I need a solution to mock this method which is called by my class under test:

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

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

The method is called from the class under test like this:

PersistenceController<EventRepository> eventController =
    PersistenceManager.createController(Event.class, EventRepository::new);

对于测试,我首先创建我的模拟对象,当调用上述方法时,该对象应返回:

For the test, I first create my mock object which should be returned when the above method was called:

final PersistenceController<EventRepository> controllerMock =
    mock(PersistenceController.class);

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

That was easy. The problem is the matcher for the method arguments because the method uses generics in combination with a supplier as parameters. The following code compiles and returns null as expected:

when(PersistenceManager.createController(any(), any()))
    .thenReturn(null);

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

Of course, I do not want to return null. I want to return my mock object. That does not compile because of the generics. To comply with the types I have to write something like this:

when(PersistenceManager.createController(Event.class, EventRepository::new))
    .thenReturn(controllerMock);

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

This compiles but the parameters in my when are not matchers, so matching does not work and null is returned. I do not know how to write a matcher that will match my parameters and return my mock object. Do you have any idea?

非常感谢你 马库斯

推荐答案

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

The problem is that the compiler is not able to infer the type of the any() of the second parameter. You can specify it using the Matcher.<...>any() syntax:

when(PersistenceManager.createController(
    any(), Matchers.<Supplier<EventRepository>>any())
).thenReturn(controllerMock);

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

If you're using Mockito 2 (where Matchers is deprecated), then use ArgumentMatchers instead:

when(PersistenceManager.createController(
    any(), ArgumentMatchers.<Supplier<EventRepository>>any())
).thenReturn(controllerMock);

这篇关于Mockito匹配器以匹配具有泛型和供应商的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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