Skip to content

Instantly share code, notes, and snippets.

@andresteingress
Last active August 29, 2015 13:57
Show Gist options
  • Save andresteingress/9685650 to your computer and use it in GitHub Desktop.
Save andresteingress/9685650 to your computer and use it in GitHub Desktop.
TestHelper's shouldFail in JDK 8
import java.util.Arrays;
import java.util.List;
public class TestHelper {
public static Throwable shouldFail(Runnable code) {
try {
code.run();
} catch (Throwable ex) {
return ex;
}
throw new AssertionError("no exception thrown!");
}
public static <T extends Throwable> T shouldFail(Class<T> clazz, Runnable code) {
try {
code.run();
} catch (Throwable ex) {
if (clazz.isInstance(ex)) {
return (T) ex;
}
throw new AssertionError("expected: " + clazz.getName() + ", got: " + ex.getClass().getName());
}
throw new AssertionError("expected: " + clazz.getName() + " but no exception thrown!");
}
public static void main(String[] args) {
shouldFail(() -> {
List<Integer> list = Arrays.asList(1, 2, 3);
list.get(3);
});
shouldFail(ArrayIndexOutOfBoundsException.class, () -> {
List<Integer> list = Arrays.asList(1, 2, 3);
list.get(3);
});
try {
shouldFail(IllegalArgumentException.class, () -> {
List<Integer> list = Arrays.asList(1, 2, 3);
list.get(3);
});
} catch (AssertionError e) {}
try {
shouldFail(IllegalArgumentException.class, () -> {
List<Integer> list = Arrays.asList(1, 2, 3);
list.get(0);
});
} catch (AssertionError e) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment