In JUnit 3
, I cannot tell JUnit
what type of exception is expected. In JUnit 4
, the declaration @Test(expected=NullPointerException.class)
does it.
But, unfortunately in Android development
, I can use only JUnit 3
. So I wrote this simple method:
public class TestingUtils {
public static void assertExpectedException(
Class<? extends Exception> exceptionClass, Runnable runnable) {
try {
runnable.run();
throw new AssertionFailedError(
"Expected exception: <" + exceptionClass.getName() + ">");
} catch (Exception e) {
if (!exceptionClass.equals(e.getClass())) {
throw new AssertionFailedError(
"Expected exception: <" + exceptionClass.getName() + "> " +
"but was: <" + e.getClass().getName() + ">"
);
}
}
}
}
Using:
public void testConstructorThrowsExceptionIfArgumentIsNull() {
TestingUtils.assertExpectedException(IllegalArgumentException.class, new Runnable() {
@Override
public void run() {
new SomeTestedClass(null);
}
});
}