您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中进行单元测试时,我们通常使用JUnit框架。当一个方法抛出异常时,我们可以使用@Test
注解的expected
属性或者ExpectedException
规则来测试这个异常。
下面是两种方法的示例:
@Test
注解的expected
属性:import org.junit.Test;
import static org.junit.Assert.*;
public class ExceptionTest {
@Test(expected = ArithmeticException.class)
public void testDivideByZero() {
int result = 10 / 0;
}
}
在这个例子中,我们测试divideByZero
方法是否抛出了ArithmeticException
异常。如果抛出了这个异常,测试将通过;否则,测试将失败。
ExpectedException
规则:import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ExceptionTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testDivideByZero() {
thrown.expect(ArithmeticException.class);
int result = 10 / 0;
}
}
在这个例子中,我们使用ExpectedException
规则来测试divideByZero
方法是否抛出了ArithmeticException
异常。在testDivideByZero
方法中,我们首先调用thrown.expect()
方法来指定期望的异常类型。如果抛出了这个异常,测试将通过;否则,测试将失败。
这两种方法都可以用来测试异常,你可以根据自己的喜好和项目需求选择合适的方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。