junit5和junit4_JUnit声明异常– JUnit 5和JUnit 4

本文介绍了如何在JUnit 5和JUnit 4中测试预期的异常,包括使用JUnit 5的断言方法进行异常测试和异常消息的验证,以及JUnit 4的@Test注解和Exception Rule来定义预期的异常。
摘要由CSDN通过智能技术生成

junit5和junit4

We can test expected exceptions using JUnit 5 assertThrows assertion. This JUnit assertion method returns the thrown exception, so we can use it to assert exception message too.

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

JUnit断言异常 (JUnit Assert Exception)

Here is a simple example showing how to assert exception in JUnit 5.

这是一个简单的示例,显示了如何在JUnit 5中声明异常。

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

JUnit 5断言异常消息 (JUnit 5 Assert Exception Message)

Let’s say we have a class defined as:

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

class Foo {
	void foo() throws Exception {
		throw new Exception("Exception Message");
	}
}

Let’s see how we can test exception as well as its message.

让我们看看我们如何测试异常及其消息。

Foo foo = new Foo();
Exception exception = assertThrows(Exception.class, () -> foo.foo());
assertEquals("Exception Message", exception.getMessage());

JUnit 4预期异常 (JUnit 4 Expected Exception)

We can use JUnit 4 @Test annotation expected attribute to define the expected exception thrown by the test method.

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

@Test(expected = Exception.class)
public void test() throws Exception {
	Foo foo = new Foo();
	foo.foo();
}

JUnit 4断言异常消息 (JUnit 4 Assert Exception Message)

If we want to test exception message, then we will have to use ExpectedException rule. Below is a complete example showing how to test exception as well as exception message.

如果我们要测试异常消息,那么我们将不得不使用ExpectedException规则。 以下是显示如何测试异常以及异常消息的完整示例。

package com.journaldev.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("Exception Message");
		foo.foo();
	}
}

That’s all for a quick roundup on testing expected exceptions in JUnit 5 and JUnit 4.

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

GitHub Repository project. GitHub Repository项目中查看更多JUnit 5示例。

翻译自: https://www.journaldev.com/21826/junit-assert-exception-expected

junit5和junit4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值