首页 > Java > java教程 > 如何在 JUnit 测试中有效断言异常?

如何在 JUnit 测试中有效断言异常?

DDD
发布: 2024-12-26 22:49:10
原创
207 人浏览过

How Can I Efficiently Assert Exceptions in JUnit Tests?

在 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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板