Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito matcher to match a method with generics and a supplier

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

like image 988
McPringle Avatar asked Jul 15 '17 07:07

McPringle


Video Answer


1 Answers

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);
like image 133
janos Avatar answered Sep 20 '22 19:09

janos