Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an exception from Mockito

Tags:

java

mockito

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?

like image 438
Ahmad Usama Beg Avatar asked Dec 17 '12 06:12

Ahmad Usama Beg


People also ask

How do you throw an exception in JUnit?

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.

How do you throw an exception in the void method?

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.

How do you throw an exception in JUnit 5?

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.


1 Answers

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); 
like image 64
Makoto Avatar answered Sep 22 '22 03:09

Makoto