JUnit断言异常– JUnit 5和JUnit 4
时间:2020-02-23 14:35:23 来源:igfitidea点击:
我们可以使用JUnit 5assertThrows断言来测试预期的异常。
这个JUnit断言方法返回抛出的异常,因此我们也可以使用它来断言异常消息。
JUnit断言异常
这是一个简单的示例,显示了如何在JUnit 5中声明异常。
String str = null; assertThrows(NullPointerException.class, () -> str.length());
JUnit 5断言异常消息
假设我们有一个定义为的类:
class Foo {
void foo() throws Exception {
throw new Exception("Exception Message");
}
}
让我们看看我们如何测试异常及其消息。
Foo foo = new Foo();
Exception exception = assertThrows(Exception.class, () -> foo.foo());
assertEquals("Exception Message", 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.theitroad.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();
}
}

