Mockito test a void method throws an exception

JavaExceptionMockingMockito

Java Problem Overview


I have a method with a void return type. It can also throw a number of exceptions so I'd like to test those exceptions being thrown. All attempts have failed with the same reason:

>The method when(T) in the type Stubber is not applicable for the arguments (void)

Any ideas how I can get the method to throw a specified exception?

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));

Java Solutions


Solution 1 - Java

The parentheses are poorly placed.

You need to use:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and NOT use:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation

Solution 2 - Java

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

Solution 3 - Java

You can try something like below:-
   
 given(class.method()).willAnswer(invocation -> {
          throw new ExceptionClassName();
        });
    
In my case, I wanted to throw an explicit exception for a try block,my method block was something like below
    
     public boolean methodName(param) throws SomeException{
    
        try(FileOutputStream out = new FileOutputStream(param.getOutputFile())) {
          //some implementation
        } catch (IOException ioException) {
          throw new SomeException(ioException.getMessage());
        } catch (SomeException someException) {
          throw new SomeException (someException.getMessage());
        } catch (SomeOtherException someOtherException) {
          throw new SomeException (someOtherException.getMessage());
        }
        return true;
      }

I have covered all the above exceptions for sonar coverage like below
    
   given(new FileOutputStream(fileInfo.getOutputFile())).willAnswer(invocation -> {
      throw new IOException();
    });
    Assertions.assertThrows(SomeException.class, () ->
    {
      ClassName.methodName(param);
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionedwardmlyteView Question on Stackoverflow
Solution 1 - JavaJB NizetView Answer on Stackoverflow
Solution 2 - JavaOndrej BurkertView Answer on Stackoverflow
Solution 3 - JavaAyushiView Answer on Stackoverflow