JUnit4断言确定异常

简介: JUnit4断言确定异常
  1. @Test(expected=Exception)
@Test(expected=ArrayIndexOutOfBoundsException.class)
public void display() {
  arr.display();
  arr.get(-1); // 抛异常:ArrayIndexOutOfBoundsException
}

被认为是一种不好的做法:期待一般的Exception,RuntimeException甚至是Throwable。代码可能会在预期的其他地方抛出异常而测试仍然会通过!


无法断言异常消息


  1. ExpectedException Rule
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void display() {
   arr.display();
   exception.expect(ArrayIndexOutOfBoundsException.class);
   // exception.expectMessage("数据指针越界!");
   arr.get(-1); // 抛异常:ArrayIndexOutOfBoundsException
}


这种方式比@Test(expected=ArrayIndexOutOfBoundsException.class)更好,如果是在调用arr.display(方法之前就已经抛出异常的话,测试结果就不是我们想要的了。


ExpectedException还能够验证异常信息,如exception.expectMessage(“there is an exception!”);


JUnit 5 assertThrows


import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
class Junit5ExceptionTestingTest { // non public, new to JUnit5
    @Test
    @DisplayName("Junit5 built-in Assertions.assertThrows and Assertions.assertAll")
    @Tag("exception-testing")
    void exceptionTest() {
        Throwable throwable = assertThrows(MyRuntimeException.class, new Thrower()::throwsRuntime);
        assertAll(
            () -> assertEquals("My custom runtime exception", throwable.getMessage()),
            () -> assertNull(throwable.getCause())
        );
    }
}


相关文章
|
Java 测试技术 Android开发
Junit - 期望异常测试(Expected Test)
Junit - 期望异常测试(Expected Test)
1119 0
|
29天前
|
测试技术
如何使用 JUnit 测试方法是否存在异常
【8月更文挑战第22天】
16 0
TestEngine with ID ‘junit-jupiter‘ failed to discover tests异常问题处理
今天在接手的项目中本想在测试类中跑一遍持久层的逻辑,但是测试类型项目启动就报错
|
1月前
|
XML Java 测试技术
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
这篇文章介绍了Spring5框架的三个新特性:支持@Nullable注解以明确方法返回、参数和属性值可以为空;引入函数式风格的GenericApplicationContext进行对象注册和管理;以及如何整合JUnit5进行单元测试,同时讨论了JUnit4与JUnit5的整合方法,并提出了关于配置文件加载的疑问。
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
|
7天前
|
SQL JavaScript 前端开发
基于Java访问Hive的JUnit5测试代码实现
根据《用Java、Python来开发Hive应用》一文,建立了使用Java、来开发Hive应用的方法,产生的代码如下
28 6
|
29天前
|
测试技术
单元测试问题之使用TestMe时利用JUnit 5的参数化测试特性如何解决
单元测试问题之使用TestMe时利用JUnit 5的参数化测试特性如何解决
21 2
|
30天前
|
Java 测试技术 Maven
Junit单元测试 @Test的使用教程
这篇文章是一个关于Junit单元测试中`@Test`注解使用的教程,包括在Maven项目中添加Junit依赖、编写带有@Test注解的测试方法,以及解决@Test注解不生效的常见问题。