在 JUnit 测试中断言异常
传统上,JUnit 中的异常测试涉及详细的 try-catch 块,如所提供的代码中所示。但是,存在多种替代方案可以简化此过程。
JUnit 5 和 4.13
自 JUnit 4.13 起,可以使用 @Test(expected = IndexOutOfBoundsException.class) 注释断言在执行带注释的方法期间抛出特定异常。例如:
@Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); }
AssertJ 和 Google Truth
AssertJ 和 Google Truth 是流行的断言库,它们提供更具可读性和表现力的断言,包括用于测试异常的断言。例如,使用 AssertJ:
import static org.assertj.core.api.Assertions.assertThatThrownBy; @Test public void testIndexOfBoundsException() { ArrayList emptyList = new ArrayList(); assertThatThrownBy(() -> emptyList.get(0)).isInstanceOf(IndexOutOfBoundsException.class); }
以上是如何在 JUnit 测试中有效断言异常?的详细内容。更多信息请关注PHP中文网其他相关文章!