Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
        // ...
    }
}
like image 695
John Bupit Avatar asked Sep 18 '25 10:09

John Bupit


1 Answers

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());
like image 67
Jeff Bowman Avatar answered Sep 20 '25 01:09

Jeff Bowman