Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 489 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
reason: no instance(s) of type variable(s) T exist so that void conforms to using mockito

#1
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
Reply

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

#3
I Figured out the right syntax.
```
Service mockedService = new DefaultServie();
doNothing().when(mockedService).sendReportingLogs(null);
```
Hope this answers the questions
Reply

#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.
Reply

#5
For **void** methods, I think you need to use the `doThrow` syntax.

So in your case it would be:

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



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through