Skip to content

Instantly share code, notes, and snippets.

@Rene-Frerichs
Last active November 26, 2015 15:44
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 Rene-Frerichs/cb5c3434fd40cb3100f8 to your computer and use it in GitHub Desktop.
Save Rene-Frerichs/cb5c3434fd40cb3100f8 to your computer and use it in GitHub Desktop.
Different alternatives for exception testing with JUnit
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ExceptionTestingTest {
@Rule
public ExpectedException thrownException = ExpectedException.none();
/**
* This is the method under test.
*/
public void methodThrowsIllegalArgument() {
throw new IllegalArgumentException("Invalid Argument");
}
/**
* Classic JUnit exception test with try catch.
*/
@Test
public void tryCatch() {
try {
methodThrowsIllegalArgument();
fail("Expected IllegalArgumentException!");
} catch (IllegalArgumentException exception) {
assertThat(exception.getMessage(), is("Invalid Argument"));
}
}
/**
* Expected exception test.
*/
@Test(expected = IllegalArgumentException.class)
public void expected() {
methodThrowsIllegalArgument();
}
/**
* Test with expected exception rule.
*/
@Test
public void exceptionRule() {
thrownException.expect(IllegalArgumentException.class);
thrownException.expectMessage("Invalid Argument");
methodThrowsIllegalArgument();
}
/**
* Test with assertJ using java 8 lambda expression.
*/
@Test
public void assertJ() {
assertThatThrownBy(this::methodThrowsIllegalArgument)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid Argument");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment