javaspringspring-bootjunitmockito

reason: no instance(s) of type variable(s) T exist so that void conforms to using mockito


I want to throw an Exception when running a void method

when(booking.validate(any())).thenThrow(BookingException.builder().build());

but I have a compilation error:

Required type: T
Provided: void
reason: no instance(s) of type variable(s) T exist so that void conforms to T

Solution

  • For void methods, I think you need to use the doThrow syntax.

    So in your case it would be:

    doThrow(BookingException.builder().build())
          .when(booking)
          .validate(any());