I want to throw a ContentIOException
from a method whose signature look like this.
public void putContent(InputStream is) throws ContentIOException.
When I try to throw ContentIOException
from Mockito like such:
when(StubbedObject.putContent(contentStream)).thenThrow(ContentIOException.class);
I get the following compilation error:
The method when(T) in the type Mockito is not applicable for the arguments (void).
What am I doing wrong?
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
Take a look at this reference in the official API. You want to reverse the way your call is made and adjust the argument too, since this is a void
method that you expect to throw an exception.
doThrow(new ContentIOException()).when(StubbedObject).putContent(contentStream);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With