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中测试预期异常的快速汇总。
翻译自: https://www.journaldev.com/21826/junit-assert-exception-expected
junit5和junit4