Last active
November 26, 2015 15:44
-
-
Save Rene-Frerichs/cb5c3434fd40cb3100f8 to your computer and use it in GitHub Desktop.
Different alternatives for exception testing with JUnit
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 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