Skip to content

Instantly share code, notes, and snippets.

@Toparvion
Created April 11, 2016 18:03
Show Gist options
  • Save Toparvion/9bbe899f97406e2e733058c793df9db6 to your computer and use it in GitHub Desktop.
Save Toparvion/9bbe899f97406e2e733058c793df9db6 to your computer and use it in GitHub Desktop.
A very simple java8-style snippet to assert exception inside test method. Works without JUnit boilerplate (like rules, @expected annotations and so on) and without explicit try-catch block.
package tech.toparvion.gist;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import static tech.toparvion.gist.TestHelper.assertException;
public class InputStreamTest {
@Test
public void testThrowing() throws Exception {
// SUT - system under test - a trivial input stream.
InputStream stream = new ByteArrayInputStream(new byte[0]);
// Let's make it unusable
stream.close();
// ... and try to use:
final byte[] readBuf = new byte[10];
// Thanks to lambdas we can either call methods as usual
assertException(() -> stream.read(readBuf), IOException.class);
// .. or through a method reference
assertException(stream::available, IOException.class);
// We'd be here just in case tested methods have really thrown excpected exceptions.
// Do any stuff you need further.
}
}
package tech.toparvion.gist;
import org.junit.Assert;
import static java.lang.String.format;
public class TestHelper {
/**
* Asserts that proposed <code>action</code> throws exception of <code>exceptedExceptionClass</code>. If action
* doesn't throw, an {@link AssertionError} is thrown.
* @param action tested action; can be expressed with a lambda expression
* @param exceptedExceptionClass a class of exception expected to be thrown
*/
public static void assertException(TestedAction action,
Class<? extends Exception> exceptedExceptionClass) {
try {
action.act();
Assert.fail("Tested action has not thrown any exception.");
} catch (Throwable e) {
if (!exceptedExceptionClass.isAssignableFrom(e.getClass())) {
Assert.fail(format("Tested action has thrown exception of class '%s' while expected class is '%s'.",
e.getClass().getName(), exceptedExceptionClass.getName()));
}
}
}
@FunctionalInterface
public interface TestedAction {
void act() throws Exception;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment