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

We Are Going To Discuss About reason: no instance(s) of type variable(s) T exist so that void conforms to using mockito. So lets Start this Java Article.

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

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

    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.

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

    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.

Solution 1

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.

Original Author Of This Content

Solution 2

I Figured out the right syntax.

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

Hope this answers the questions

Original Author Of This Content

Solution 3

/**
 * 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);
}

Original Author Of This Content

Solution 4

Just complementing @Shane ‘s comment, which was a life saver but not very clear.

Example on how to throw PersistenceException from a repository method:

doThrow(new PersistenceException())
            .when(outboxRepository)
            .delete(isA(WorkersEphemeralOutboxEntry.class));

I find this especially helpful when you have overloaded methods and the compiler cannot figure out which one to call with any() and any(Class.class) gives you compiling error.

Original Author Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment