Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 465
Sandro Rey Avatar asked Apr 01 '20 18:04

Sandro Rey


3 Answers

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());

I hope this helps.

like image 184
Shane Creedon Avatar answered Nov 18 '22 18:11

Shane Creedon


I Figured out the right syntax.

Service mockedService = new DefaultServie();
doNothing().when(mockedService).sendReportingLogs(null);

Hope this answers the questions

like image 27
M-sAnNan Avatar answered Nov 18 '22 19:11

M-sAnNan


/**
 * Use <code>doThrow()</code> when you want to stub the void method with an exception.
 * <p>
 * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler
 * does not like void methods inside brackets...
 * <p>
 * Example:
 *
 * <pre class="code"><code class="java">
 *   doThrow(new RuntimeException()).when(mock).someVoidMethod();
 * </code></pre>
 *
 * @param toBeThrown to be thrown when the stubbed method is called
 * @return stubber - to select a method for stubbing
 */
@CheckReturnValue
public static Stubber doThrow(Throwable... toBeThrown) {
    return MOCKITO_CORE.stubber().doThrow(toBeThrown);
}
like image 1
user16582031 Avatar answered Nov 18 '22 19:11

user16582031