How do you assert that a certain exception is thrown in JUnit 4 tests?
How can I use JUnit4 idiomatically to test that some code throws an exception?
While I can certainly do something like this:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
JUnit 4 has support for this:
@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}
Reference: https://junit.org/junit4/faq.html#atests_7
Edit Now that JUnit5 has released, the best option would be to use Assertions.assertThrows()
(see my other answer).
If you haven't migrated to JUnit 5, but can use JUnit 4.7, you can use the ExpectedException
Rule:
public class FooTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void doStuffThrowsIndexOutOfBoundsException() {
Foo foo = new Foo();
exception.expect(IndexOutOfBoundsException.class);
foo.doStuff();
}
}
This is much better than @Test(expected=IndexOutOfBoundsException.class)
because the test will fail if IndexOutOfBoundsException
is thrown before foo.doStuff()
See this article for details
Be careful using expected exception, because it only asserts that the method threw that exception, not a particular line of code in the test.
I tend to use this for testing parameter validation, because such methods are usually very simple, but more complex tests might better be served with:
try {
methodThatShouldThrow();
fail( "My method didn't throw when I expected it to" );
} catch (MyException expectedException) {
}
Apply judgement.
链接地址: http://www.djcxy.com/p/14338.html上一篇: Java异常有多慢?