Last active
August 29, 2015 14:04
-
-
Save danieldietrich/ede2f08e0b79b860f1d4 to your computer and use it in GitHub Desktop.
Assert that a block of code is throwing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 + '"'; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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