JUnit异常断言
使用Junit时,有多种方式来进行异常的断言
- ExeceptedException & @Rule,可以同时断言异常类型和消息
public class ExpectedExceptionsTest {
@Rule
public ExpectedException thrown = ExpectedException.none(); //@Rule 注解的 ExpectedException 变量声明,它必须为 public
@Test
public void verifiesTypeAndMessage() {
thrown.expect(RuntimeException.class);
thrown.expectMessage("Runtime exception occurred");
throw new RuntimeException("Runtime exception occurred");
}
}
参考:JUnit:使用ExpectedException进行异常测试
- Test(excepted=XXException.class),只能断言异常类型,不能断言消息
public class ExpectedExceptionsTest {
@Test(excepted=RuntimeException.class)
public void verifiesTypeAndMessage() {
throw new RuntimeException("Runtime exception occurred");
}
}
如果你觉得这篇文章对你有帮助或者使你有所启发,请点击右下角的推荐按钮,谢谢,:)