我們可以使用 JUnit 5 assertThrows
聲明測試預期的例外。
朱元 例外
以下是一個簡單的例子,顯示如何在 JUnit 5 中主張例外。
1String str = null;
2assertThrows(NullPointerException.class, () -> str.length());
JUnit 5 声明例外信息
假设我们有一个定义为:
1class Foo {
2 void foo() throws Exception {
3 throw new Exception("Exception Message");
4 }
5}
让我们看看我们如何测试例外以及其信息。
1Foo foo = new Foo();
2Exception exception = assertThrows(Exception.class, () -> foo.foo());
3assertEquals("Exception Message", exception.getMessage());
第4章 期待的例外
我们可以使用 JUnit 4 @Test 注释预期
属性来定义测试方法所投出的预期例外。
1@Test(expected = Exception.class)
2public void test() throws Exception {
3 Foo foo = new Foo();
4 foo.foo();
5}
JUnit 4 Assert 例外消息
如果我们想测试例外消息,那么我们将不得不使用ExpectedException
规则. 下面是一个完整的示例,显示如何测试例外以及例外消息。
1package com.journaldev.junit4;
2
3import org.junit.Rule;
4import org.junit.Test;
5import org.junit.rules.ExpectedException;
6
7public class JUnit4TestException {
8
9 @Rule
10 public ExpectedException thrown = ExpectedException.none();
11
12 @Test
13 public void test1() throws Exception {
14 Foo foo = new Foo();
15 thrown.expect(Exception.class);
16 thrown.expectMessage("Exception Message");
17 foo.foo();
18 }
19}
这一切都是为了在 JUnit 5 和 JUnit 4 中测试预期的例外。
您可以从我们的 GitHub 存储库项目中查看更多 JUnit 5 示例。