JUnit断言异常完全指南:JUnit 5与JUnit 4对比详解

📂 365bet足球比分 ⏳ 2025-11-10 09:48:04 👽 admin 👁️ 8614 💾 930
JUnit断言异常完全指南:JUnit 5与JUnit 4对比详解

JUnit 断言异常 – JUnit 5 和 JUnit 4

我们可以使用JUnit 5的assertThrows断言来测试预期的异常。这个JUnit断言方法会返回抛出的异常,所以我们可以用它来断言异常信息。

JUnit 断言异常

这里给出了一个简单的示例,展示了在JUnit 5中如何断言异常。

String str = null;

assertThrows(NullPointerException.class, () -> str.length());

JUnit 5 断言异常信息

假设我们有一个如下定义的类:

class Foo {

void foo() throws Exception {

throw new Exception("异常消息");

}

}

让我们看看如何测试异常以及它的消息。

Foo foo = new Foo();

Exception exception = assertThrows(Exception.class, () -> foo.foo());

assertEquals("异常消息", exception.getMessage());

JUnit 4 预期异常

我们可以使用JUnit 4的@Test注解的expected属性来定义测试方法抛出的预期异常。

@Test(expected = Exception.class)

public void test() throws Exception {

Foo foo = new Foo();

foo.foo();

}

JUnit 4 断言异常消息

如果我们想要测试异常消息,那么我们将需要使用ExpectedException规则。下面是一个完整的示例,展示了如何测试异常以及异常消息。

package com.Olivia.junit4;

import org.junit.Rule;

import org.junit.Test;

import org.junit.rules.ExpectedException;

public class JUnit4TestException {

@Rule

public ExpectedException thrown = ExpectedException.none();

@Test

public void test1() throws Exception {

Foo foo = new Foo();

thrown.expect(Exception.class);

thrown.expectMessage("异常消息");

foo.foo();

}

}

这就是JUnit 5和JUnit 4中测试预期异常的快速总结。

你可以在我们的GitHub仓库项目中查看更多的JUnit 5示例。

相关数据包

提振消费背景下,食品饮料行业将如何演化
豌豆荚设计奖

豌豆荚设计奖

📅 07-20 🔗 日博365bet体育在线
全部出局,如何评价亚洲球队世界杯表现?日澳高光东道主最惨
撒哟娜拉是什么意思?

撒哟娜拉是什么意思?

📅 10-12 🔗 365现金球网
← 广联达工程项目管理软件怎么用 馨字笔画写法 →