Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(...)); 
like image 721
edwardmlyte Avatar asked Mar 01 '13 11:03

edwardmlyte


People also ask

Can Mockito throw exceptions on void methods?

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 a test case?

In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException. class) annotation. You can replace IllegalArgumentException. class with any other exception e.g. NullPointerException.


1 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

like image 148
JB Nizet Avatar answered Sep 22 '22 17:09

JB Nizet