Skip to content

Instantly share code, notes, and snippets.

@kjunine
Created December 12, 2012 09:48
Show Gist options
  • Select an option

  • Save kjunine/4266461 to your computer and use it in GitHub Desktop.

Select an option

Save kjunine/4266461 to your computer and use it in GitHub Desktop.
Asserts exception without try-catch or @Test.expected() in junit.
package net.kjunine.test;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
public class AdditionalAssert {
/**
* Asserts that expected exception occurs. If it doesn't, an
* {@link AssertionError} is thrown.
*
* @param expected
* type of the expected exception
* @param code
* the code to run
*/
public static void assertException(Class<? extends Throwable> expected,
Code code) {
try {
code.test();
fail("expected: " + expected + ", but no exception occured.");
} catch (AssertionError e) {
if (!expected.isAssignableFrom(e.getClass())) {
throw e;
}
} catch (Throwable e) {
if (!expected.isAssignableFrom(e.getClass())) {
fail("expected: " + expected + ", but was: " + e.getClass());
}
}
}
/**
* Similar to {@link Runnable}, but this can throw checked exceptions.
*/
public static interface Code {
void test() throws Exception;
}
@Test
public void test() {
assertException(IllegalArgumentException.class, new Code() {
public void test() throws Exception {
throw new IllegalArgumentException();
}
});
assertException(RuntimeException.class, new Code() {
public void test() throws Exception {
throw new IllegalArgumentException();
}
});
assertException(AssertionError.class, new Code() {
public void test() throws Exception {
assertException(IllegalArgumentException.class, new Code() {
public void test() throws Exception {
throw new RuntimeException();
}
});
}
});
assertException(IOException.class, new Code() {
public void test() throws Exception {
throw new IOException();
}
});
assertException(OutOfMemoryError.class, new Code() {
public void test() throws Exception {
throw new OutOfMemoryError();
}
});
assertException(AssertionError.class, new Code() {
public void test() throws Exception {
throw new AssertionError();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment