Skip to content

Instantly share code, notes, and snippets.

@danieldietrich
Last active August 29, 2015 14:04
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 danieldietrich/ede2f08e0b79b860f1d4 to your computer and use it in GitHub Desktop.
Save danieldietrich/ede2f08e0b79b860f1d4 to your computer and use it in GitHub Desktop.
Assert that a block of code is throwing
public final class Assertions {
/**
* This class is not intended to be instantiated.
*/
private Assertions() {
throw new AssertionError(Assertions.class.getName() + " cannot be instantiated.");
}
public static RunnableAssert assertThat(Runnable test) {
return new RunnableAssert(test);
}
public static class RunnableAssert {
final Runnable test;
RunnableAssert(Runnable test) {
this.test = test;
}
public void isThrowing(Class<? extends Throwable> expectedException, String expectedMessage) {
if (expectedException == null) {
throw new IllegalArgumentException("expectedException is null");
}
try {
test.run();
throw new AssertionError(expectedException.getName() + " not thrown");
} catch (AssertionError x) {
throw x;
} catch (Throwable x) {
if (!expectedException.isAssignableFrom(x.getClass())) {
throw new AssertionError("Expected exception assignable to type "
+ expectedException.getName()
+ " but was "
+ x.getClass().getName()
+ " with message "
+ Strings.toString(x.getMessage())
+ ".");
}
final String actualMessage = x.getMessage();
final boolean isOk = (actualMessage == null) ? (expectedMessage == null)
: actualMessage.equals(expectedMessage);
if (!isOk) {
throw new AssertionError("Expected exception message "
+ wrapString(expectedMessage)
+ " but was "
+ wrapString(actualMessage)
+ ".");
}
}
}
private String wrapString(String s) {
return (s == null) ? "null" : '"' + s + '"';
}
}
}
import org.junit.Test;
public class AssertionsTest {
@Test
public void shouldAssertIsThrowing() {
Assertions.assertThat(() -> {
throw new RuntimeException("Error");
}).isThrowing(RuntimeException.class, "Error");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment