Should jUnit test cases handle default exceptions in a throws declaration or in a try catch block
exception, java, junit
Solution
JUnit has a great article here: https://github.com/junit-team/junit/wiki/Exception-testing on this very subject. You can do:
@Test(expected= IndexOutOfBoundsException.class)
public void empty() {
new ArrayList<Object>().get(0);
}
or:
@Test
public void testExceptionMessage() {
try {
new ArrayList<Object>().get(0);
fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {
assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));
}
}
Problem
If I write test cases for a function that throws a bunch of exceptions should I add a throws declaration for these exceptions in my test method or should I catch each individual exception. What is the correct way of going about it? I believe try-catch is a better way but in the catch block should I print the stacktrace? For example, I have a method `getGroups(String name)` that throws `AuthenticationException`. If I write a test case to check if an `IllegalArgumentException` is being thrown when the `name` parameter is null, how do I handle the `AuthenticationException`? Do I add it to throws part of my method or should I enclose the exception in a `try-catch` block. ``` @Test public void testGetGroupsWithNull() throws AuthenticationException { thrown.expect(IllegalArgumentException.class); getGroups(null); } ``` In the above test case I just added a `throws AuthenticationException`, but I would like to know if it is better to enclose the exception in a try-catch block and what shoudld I do after catching the exception. I could print the stack trace. I am handling the unexpected exception `AuthenticationException`by not placing it in the 'throws' clause but in a try/catch block. ``` @Test public void testGetGroupsWithNull() { thrown.expect(IllegalArgumentException.class); try { getGroups(null); } catch(AuthenticationExcption e) { Assert.fail("Authentication Exception"); } } ```