John Bupit
John Bupit

Reputation: 10618

Mockito.any() to match any instance of generics type T

I'm trying to mock a void method to throw an exception every time. The method takes a List<SomeClass> as an argument. How to I pass its to Mockito.any()?

Mockito.doThrow(new Exception())
       .when(myClassInstanceSpy)
       .myVoidMethod(Mockito.any(List<SomeClass>.class)); // This fails!

Here's my class definition:

class MyClass {
    ... 
    public void myVoidMethod(List<SomeClass> scList) {
        // ...
    }
}

Upvotes: 4

Views: 12330

Answers (2)

Jeff Bowman
Jeff Bowman

Reputation: 95654

You can specify generics using explicit method types:

Mockito.doThrow(new Exception())
   .when(myClassInstanceSpy)
   .myVoidMethod(Mockito.<List<SomeClass>>any());

Or with the handler for List in particular:

Mockito.doThrow(new Exception())
   .when(myClassInstanceSpy)
   .myVoidMethod(Mockito.anyListOf(SomeClass.class));

Java 8 allows for parameter type inference, so if you're using Java 8, this may work as well:

Mockito.doThrow(new Exception())
   .when(myClassInstanceSpy)
   .myVoidMethod(Mockito.any());

Upvotes: 9

Dimitri
Dimitri

Reputation: 8280

Try :

Mockito.doThrow(new Exception())
   .when(myClassInstanceSpy)
   .myVoidMethod(Mockito.anyListOf(SomeClass.class));

Upvotes: 4

Related Questions