在 JUnit 中断言异常
原文:https://www.studytonight.com/java-examples/assert-exceptions-in-junit
在 JUnit 4 中,我们可以通过使用 @Test 注释的预期属性来测试一个方法是否抛出异常。我们可以使用断言.资产抛出()在 JUnit 5 中测试同样的事情。
在本教程中,我们将学习如何使用 JUnit 检查异常是否发生。
JUnit 4 预期异常
我们可以使用带有 @Test 注释的期望属性来定义我们期望从测试方法中得到的异常。如果异常发生在测试方法中,那么测试通过。
如果预期的异常没有发生,测试将失败。让我们看看这两种情况。
在下面的代码中,我们期望出现 ArrayIndexOutOfBounds 异常。当我们试图访问大小为 5 的数组的索引 100 处的元素时,会出现异常。在这种情况下,测试将通过。
import org.junit.Test;
public class Demo
{
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testMethod()
{
int[] intArr = {10, 20, 30, 40, 50};
int x = intArr[100];//Exception
}
}
现在,如果我们尝试访问索引 2 处的元素,则不会出现错误。在这种情况下,测试将会失败,因为我们预期会出现异常。
import org.junit.Test;
public class Demo
{
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testMethod()
{
int[] intArr = {10, 20, 30, 40, 50};
int x = intArr[2];
}
}
故障跟踪:
java.lang.AssertionError:预期异常:Java . lang . arrayindexoutofboundsexception
如果我们需要验证异常的一些附加属性,那么我们可以使用 ExpectedException 规则。让我们创建一个方法,抛出一个带有“越界”异常消息的 ArrayIndexOutOfBounds 异常。让我们尝试使用 ExpectedException 规则来验证此消息。
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class Demo
{
@Rule
public ExpectedException rule = ExpectedException.none();
void someMethod() throws ArrayIndexOutOfBoundsException
{
throw new ArrayIndexOutOfBoundsException("Out Of Bounds");
}
@Test
public void testMethod()
{
rule.expect(ArrayIndexOutOfBoundsException.class);
rule.expectMessage("Out Of Bounds");
someMethod();
}
}
JUnit 5 预期异常
JUnit 5 引入了断言 API ,我们可以用它来测试一个方法抛出的异常。我们将使用断言方法来断言异常。
此方法采用预期的异常类和可执行代码块或 lambda 表达式作为参数。如果预期的异常发生,那么测试将通过。如果没有异常发生,或者发生了其他类型的异常,那么测试失败。
在下面的代码中,当我们试图解析一个字符串时,我们需要一个numberformateexception。
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Demo
{
@Test
void testExpectedException()
{
Assertions.assertThrows(NumberFormatException.class, () -> {
Integer.parseInt("Twenty");//Exception
});
}
}
assertThrows()方法也可以预期父类异常。因此,如果我们将异常类作为第一个参数传递,那么对于任何异常,测试都会成功(因为所有异常都扩展了异常类)。
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Demo
{
@Test
void testExpectedException()
{
Assertions.assertThrows(Exception.class,//Parent Class Exception
() -> {Integer.parseInt("Twenty");}
);
}
}
方法返回一个异常对象。我们可以用它来验证抛出的异常的附加属性。
让我们尝试使用 assertEquals()来验证异常消息。
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Demo
{
@Test
void testExpectedException()
{
Exception e = Assertions.assertThrows(NumberFormatException.class, () -> {
Integer.parseInt("Twenty");//Exception
});
String msg = e.getMessage();
assertEquals("For input string", msg);
}
}
摘要
在本教程中,我们学习了如何使用 JUnit 断言是否引发了异常。对于 JUnit 4,我们可以在@Test 注释中使用期望的属性。如果我们想要验证其他异常属性,那么我们可以使用 ExpectedException 规则。对于 JUnit 5,我们可以使用断言. assertThrows()方法。