Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito not throwing exception using thenThrow

Tags:

java

mockito

I am using Mockito to mock the method of service layer.

trying to mock the following line of code

boolean status= accountDAO.updateAccount(Account acct);

And To mock this I am using

Mockito.when(accountDAO.updateAccount(Account acct)).thenThrow(new DataBaseException());

But the problem is when code comes to the line boolean status= accountDAO.updateAccount(Account acct);, no exception gets thrown, it just works the normal way, without throwing an exception. Ideally an exception should be thrown, because I have mocked it to throw Database exception.

While there is another method "find account", i.e

Account acc=accountDAO.find(Account.class,accountId);

for this method the exception is being thrown successfully using mocikto, but for the update method it is not working.

Please help.

like image 255
R Ram Avatar asked Jul 17 '18 06:07

R Ram


1 Answers

Assuming that your code looks like this:

Account acct = ...
Mockito.when(accountDAO.updateAccount(acct)).thenThrow(new DataBaseException());

This will throw an exception if you execute above method only with Account acct, other objects will not throw anything. So if you are executing this method with different object, nothing will happen.

To check this, you can define a rule, that any execution of this method, with any instance of Account will throw an exception:

 Mockito.when(accountDAO.updateAccount(Mockito.any(Account.class))).thenThrow(new DataBaseException());
like image 186
Beri Avatar answered Oct 24 '22 07:10

Beri