在JUnit测试中处理异常,你可以使用@Test注解的expected属性或者使用try-catch语句。下面是两种方法的详细说明:
方法1:使用@Test注解的expected属性
在JUnit 4中,你可以在@Test注解中使用expected属性来指定预期的异常类型。如果测试方法抛出了指定的异常,那么测试将通过。例如:
import org.junit.Test;
import static org.junit.Assert.*;
public class ExceptionTest {
@Test(expected = ArithmeticException.class)
public void testDivideByZero() {
int result = 1 / 0;
}
}
在JUnit 5中,expected属性已被弃用,你可以使用assertThrows方法来代替:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class ExceptionTest {
@Test
public void testDivideByZero() {
ArithmeticException exception = assertThrows(ArithmeticException.class, () -> {
int result = 1 / 0;
});
assertEquals("/ by zero", exception.getMessage());
}
}
方法2:使用try-catch语句
你还可以使用try-catch语句来捕获异常,并在catch块中进行断言。这种方法可以让你更详细地检查异常的属性,例如异常消息。以下是一个示例:
import org.junit.Test;
import static org.junit.Assert.*;
public class ExceptionTest {
@Test
public void testDivideByZero() {
try {
int result = 1 / 0;
fail("Expected ArithmeticException to be thrown");
} catch (ArithmeticException e) {
assertEquals("/ by zero", e.getMessage());
}
}
}
这种方法适用于JUnit 4和JUnit 5。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。