JUnit异常断言

使用Junit时,有多种方式来进行异常的断言

  1. 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进行异常测试

  1. Test(excepted=XXException.class),只能断言异常类型,不能断言消息
public class ExpectedExceptionsTest {
    @Test(excepted=RuntimeException.class)
    public void verifiesTypeAndMessage() {
        throw new RuntimeException("Runtime exception occurred");
    }
}
posted @ 2017-09-11 13:20  liqipeng  阅读(1067)  评论(0编辑  收藏  举报