假设我们有以下代码:
public void divide(int a, int b) {
try {
int result = a / b;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
我们想要编写Junit测试用例来覆盖catch
块,我们可以这样做:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class DivideTest {
@Test
public void testDivideByZero() {
try {
Divide divide = new Divide();
divide.divide(5, 0);
Assertions.fail("Expected ArithmeticException was not thrown");
} catch (ArithmeticException e) {
Assertions.assertEquals("Cannot divide by zero", e.getMessage());
}
}
}
在此示例中,我们首先尝试执行divide()
方法来除以0。因为除以0是一种算术异常,所以我们期望抛出ArithmeticException
。通过使用Assertions.fail()
方法,我们确保在try
代码块中的异常被抛出,否则测试会失败。在catch
代码块中,我们可以检查异常消息是否正确。使用此测试,我们可以测试catch
块是否有效。