Mockito matcher to match a method with generics and a supplier

Viewed 10976

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 Answers
Related