525

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(...));
edwardmlyte
  • 14,597
  • 22
  • 57
  • 82
  • 2
    Possible duplicate of [How to make mock to void methods with mockito](https://stackoverflow.com/questions/2276271/how-to-make-mock-to-void-methods-with-mockito) – Willian Jul 24 '17 at 20:40

3 Answers3

960

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

hooknc
  • 4,540
  • 5
  • 32
  • 55
JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
  • 7
    @edwardmlyte This Mockito inconsistency is one of the reasons I've switch to [MoxieMocks](https://code.google.com/p/moxiemocks/wiki/MockingLibraryComparison) – Muel Oct 20 '14 at 17:37
  • @clement both can be used: http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#5. Creating an exception doesn't throw it. – JB Nizet Jul 23 '15 at 15:27
  • 1
    @JB Nizet I totally agree with you but however if I write doThrow(new Exception()) instead of doThrow(Exception.class), I have the following error when I launch my test ; Expected exception com.company.project.exception.ElementNotFoundException but got org.mockito.exceptions.base.MockitoException: – clement Jul 24 '15 at 08:21
  • 2
    Ask another question, with the code under test, the code of the test and the complete stack trace of the exception. – JB Nizet Jul 24 '15 at 09:17
  • 7
    doThrow(new Exception()).when(object).voidMethod(any()); – Soumyajit Swain Nov 18 '16 at 06:38
  • Works like a charm for `Mockito 2.0.2` – realPK Feb 15 '18 at 05:55
  • @JBNizet - Could you please guide here: https://stackoverflow.com/questions/57090715/mockito-unable-to-throw-exception-from-void-method – PAA Jul 18 '19 at 09:52
33

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(...));
Ondrej Burkert
  • 5,807
  • 2
  • 28
  • 25
  • 2
    Thanks for posting this here; if the method returns a value : given(mockedObject.methodReturningAnObject()).willThrow(new Exception()); if the method doesn't return anything : willThrow(new Exception()).given(mockedObject).methodReturningVoid(...)); Explanation form javadoc : "Stubbing voids requires different approach from {@link Mockito#when(Object)} (or BDDMockito.given)because the compiler does not like void methods inside brackets..." – Wolf359 Dec 17 '18 at 07:55
-1

You can try something like the 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);
    });
Cristian Traìna
  • 8,304
  • 2
  • 35
  • 56
Ayushi
  • 1
  • 1