593

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
  • 15,937
  • 23
  • 58
  • 83
  • 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

4 Answers4

1098

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,854
  • 5
  • 31
  • 60
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 11
    @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
  • 7
    doThrow(new Exception()).when(object).voidMethod(any()); – Soumyajit Swain Nov 18 '16 at 06:38
44

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
  • 6,617
  • 2
  • 32
  • 27
  • 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
2

I was having a issue trying to test @Retryable with three method calls when runtime exception occurred, I made like so and worked for me.

     Mockito.doThrow(RuntimeException.class)
            .doThrow(RuntimeException.class)
            .doNothing()
            .when(youMockInstance)
            .methodToTest(<parameter if your method has>);
EACUAMBA
  • 461
  • 4
  • 8
-2

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);
    });
Ayushi
  • 1
  • 1