Mockito test a void method throws an exception

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(...));
1

3 Answers

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

7

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(...));
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); });
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like