Mockito.any() for <T>

Rajesh Kolhapure picture Rajesh Kolhapure · May 27, 2015 · Viewed 78.5k times · Source

I want to mock a method with signature as:

public <T> T documentToPojo(Document mongoDoc, Class<T> clazz)

I mock it as below:

Mockito.when(mongoUtil.documentToPojo(Mockito.any(Document.class), Mockito.any(WorkItemDTO.class)))

But I get error as:

The method documentToPojo(Document, Class<T>) in the type MongoUtil is not applicable for the arguments (Document, WorkItemDTO)

Is there any method in Mockito which will help me mock for T?

Answer

Jeff Bowman picture Jeff Bowman · May 27, 2015

Note that documentToPojo takes a Class as its second argument. any(Foo.class) returns an argument of type Foo, not of type Class<Foo>, whereas eq(WorkItemDTO.class) should return a Class<WorkItemDTO> as expected. I'd do it this way:

when(mongoUtil.documentToPojo(
    Mockito.any(Document.class),
    Mockito.eq(WorkItemDTO.class))).thenReturn(...);