Skip to content

Instantly share code, notes, and snippets.

@awilmore
Created May 23, 2012 10:22
Show Gist options
  • Save awilmore/2774461 to your computer and use it in GitHub Desktop.
Save awilmore/2774461 to your computer and use it in GitHub Desktop.
Standard Exception Constructor Tester
package com.awilmore.testutils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import junit.framework.Assert;
public class ExceptionTester extends Assert {
public ExceptionTester(Class<?> exceptionClass) {
try {
/* Test default constructor */
Constructor<?> c1 = exceptionClass.getConstructor();
Exception e1 = (Exception)c1.newInstance();
assertNull("Unexpected value for getMessage()", e1.getMessage());
/* Test String constructor */
String expectedMessage = "Test Message";
Constructor<?> c2 = exceptionClass.getConstructor(new Class[]{String.class});
Exception e2 = (Exception)c2.newInstance(new Object[]{expectedMessage});
assertEquals("Unexpected value for getMessage()", expectedMessage, e2.getMessage());
/* Test Throwable constructor */
InterruptedException expectedCause = new InterruptedException(expectedMessage);
Constructor<?> c3 = exceptionClass.getConstructor(new Class[]{Throwable.class});
Exception e3 = (Exception)c3.newInstance(new Object[]{expectedCause});
assertEquals("Unexpected value for getCause()", expectedCause, e3.getCause());
assertEquals("Unexpected value for getMessage()", "java.lang.InterruptedException: " + expectedMessage, e3.getMessage());
/* Test String, Throwable constructor */
String expectedMessage2 = "Test Message 2";
Constructor<?> c4 = exceptionClass.getConstructor(new Class[]{String.class, Throwable.class});
Exception e4 = (Exception)c4.newInstance(new Object[]{expectedMessage2, expectedCause});
assertEquals("Unexpected value for getCause()", expectedCause, e4.getCause());
assertEquals("Unexpected value for getMessage()", expectedMessage2, e4.getMessage());
} catch(SecurityException e) {
fail("SecurityException thrown when testing exception.");
} catch(IllegalArgumentException e) {
fail("IllegalArgumentException thrown when testing exception.");
} catch(NoSuchMethodException e) {
fail("NoSuchMethodException thrown when testing exception.");
} catch(InstantiationException e) {
fail("InstantiationException thrown when testing exception.");
} catch(IllegalAccessException e) {
fail("IllegalAccessException thrown when testing exception.");
} catch(InvocationTargetException e) {
fail("InvocationTargetException thrown when testing exception.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment