Mockito matcher to match a method with generics and a supplier

时光毁灭记忆、已成空白 提交于 2019-12-07 04:29:20

问题


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

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

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

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?

Thank you very much Marcus


回答1:


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

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

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


来源:https://stackoverflow.com/questions/45115849/mockito-matcher-to-match-a-method-with-generics-and-a-supplier

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