Tag: junit

java – How do you assert that a certain exception is thrown in JUnit 4 tests?

The Question : 2060 people think this question is useful 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); }

java – 你如何断言在JUnit 4测试中引发了某种异常?

我如何通过惯用方式使用JUnit4来测试某些代码是否会抛出异常? 虽然我当然可以做这样的事情: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } 我记得有一个注释或一个Assert.xyz或者其他一些远远不够灵活的东西,而且在这种情况下JUnit的精神远不止于此 JUnit 4支持这一点: @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } 参考:https://junit.org/junit4/faq.html#atests_7   编辑现在JUnit5已经发布,最好的选择是使用Assertions.assertThrows()(请参阅我的其他答案)。 如果您尚未迁移到JUnit 5,但可以使用JUnit 4.7,则可以使用ExpectedExceptionRule: public class FooTest {