Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a method to throw an Exception in jUnit testing?

Actually this is for code coverage and I'm having a hard time, covering to catch statements. Any ideas?

for example:

I want my selectSomethingBySomething() method (which selects from db) to throw an SQLException which is pretty hard on a test method without actually touching the actual source code. Given also the constraint that what I can only control is the parameters for the WHERE clause.

like image 424
Rey Libutan Avatar asked Jan 17 '23 01:01

Rey Libutan


1 Answers

You need to first mock the class containing selectSomethingBySomething() and then record this behavior. In mockito you'll say:

SomeDao someDaoMock = mock(SomeDao.class);

willThrow(new SQLException())).given(someDaoMock).selectSomethingBySomething();

Then inject someDaoMock into your class under test and when it calls someDaoMock.selectSomethingBySomething() it'll throw previously chosen exception.

like image 127
Tomasz Nurkiewicz Avatar answered Mar 07 '23 20:03

Tomasz Nurkiewicz