Skip to content

Instantly share code, notes, and snippets.

@hborders
Last active April 30, 2019 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hborders/83f1f19ae2fc2c7dc9c4a5880f3a1fb4 to your computer and use it in GitHub Desktop.
Save hborders/83f1f19ae2fc2c7dc9c4a5880f3a1fb4 to your computer and use it in GitHub Desktop.
public class AssertFailsWith {
public interface RunnableThatThrows {
void run() throws Throwable;
}
public static <T extends Throwable> void assertFailsWith(Class<T> throwableClass, RunnableThatThrows runnable) {
try {
runnable.run();
fail();
} catch (Throwable throwable) {
assertTrue(throwableClass.isInstance(throwable));
}
}
public static void main(String[] args) {
// succeeds
assertFailsWith(IOException.class, () -> {
throw new IOException();
);
//fails
assertFailsWith(IOException.class, () -> {
throw new RuntimeException();
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment