33

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?

spottedmahn
  • 11,379
  • 7
  • 75
  • 144
Rajesh Kolhapure
  • 641
  • 1
  • 8
  • 21
  • Why do you need to mock the second parameter? – Gábor Bakos May 27 '15 at 10:23
  • Actually I want to return mock object for this method. I am not mocking second parameter. I am mocking the documentToPojo method – Rajesh Kolhapure May 27 '15 at 10:27
  • 1
    Sorry, I tried to express, wouldn't this work? `Mockito.when(mongoUtil.documentToPojo(Mockito.any(Document.class), WorkItemDTO.class))` Without the second `any`? – Gábor Bakos May 27 '15 at 10:35
  • 1
    Just like `Mockito.any(Document.class)` says to accept any `Document`, your second parameter says to accept any `WorkItemDTO`, when you really want to accept any `Class`. As the answer below says, use `Mockito.any(Class.class)`. – dcsohl May 27 '15 at 11:14
  • 1
    @GáborBakos: Yes, but you need an `eq()` wrapper. If one parameter uses a Mockito matcher, they all must use Mockito matchers. – Jeff Bowman May 27 '15 at 20:01

3 Answers3

43

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(...);
Jeff Bowman
  • 74,544
  • 12
  • 183
  • 213
  • 3
    It is not working for me. I am using Java 8 and Mockito 2.7.5 –  Jan 26 '18 at 15:21
  • it's showing mismatch in arguments while compiling itself – Mahender Reddy Yasa Jun 12 '20 at 11:40
  • @MahenderReddyYasa I'm afraid that's not enough information to diagnose; this may be related, or it may be something else. Please ask a separate question, including your code and the full text of your error, and link to this question so answerers will have the context. – Jeff Bowman Jun 12 '20 at 15:25
5

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,

Anders R. Bystrup
  • 14,996
  • 10
  • 58
  • 53
1

You can do it using ArgumentMatchers.any() qualified with the type, like so:

Mockito.when(
    mongoUtil.documentToPojo(
        Mockito.any(Document.class),
        ArgumentMatchers.<Class<WorkItemDTO>>any()
    )
).thenReturn(...);
Collin Krawll
  • 1,362
  • 13
  • 13