Reputation: 21
How do I deal with exception thrown by a try/catch statement in Java code? What is the best way to test with Junit such a scenario?
This is the code I am trying to work with, any improvement is most welcome:
try {
sessionObj = buildSessionFactory().openSession();
sessionObj.getTransaction().commit();
return true;
} catch(Exception sqlException) {
if(null != sessionObj.getTransaction()) {
sessionObj.getTransaction().rollback();
}
return false;
}
Junit code:
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void throwsExceptionWithSpecificTypeAndMessage() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("sqlException");
throw new IllegalArgumentException("sqlException");
}
Upvotes: 2
Views: 684
Reputation: 265
Exception is a checked exception you either have to catch the exception using try... catch block or declare the exception.
@Test
public void someTest() throws Exception {
// your code here
}
This way we can declare the exception and Junit will print the stack trace if exception occurs.
Or
Optionally specify expected, a Throwable, to cause a test method to succeed iff an exception of the specified class is thrown by the method.
Class<? extends Throwable> org.junit.Test.expected()
@Test(expected = someException.class)
public void someTest() throws Exception {
// your code here
}
Upvotes: 1