How to force a method to throw an Exception in jUnit testing?
jakarta-ee, java, junit, testing
Solution
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.
Problem
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.