Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito.any() for <T>

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?

like image 632
Rajesh Kolhapure Avatar asked May 27 '15 10:05

Rajesh Kolhapure


2 Answers

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(...); 
like image 196
Jeff Bowman Avatar answered Sep 17 '22 11:09

Jeff Bowman


You can match a generic Class<T> argument using simply any( Class.class ), eg.:

Mockito.when( mongoUtil.documentToPojo( Mockito.any( Document.class ),                                         Mockito.any( Class.class ) ) ); 

Cheers,

like image 32
Anders R. Bystrup Avatar answered Sep 19 '22 11:09

Anders R. Bystrup