为什么我不能在JUnit中定义期望ParseException?

时间:2014-10-09 21:35:31

标签: java junit

我需要将expect = ParseException.class添加到Junit方法,但即使将其添加到方法后,抛出的行也显示“未处理的异常类型ParseException”消息,我无法运行测试。

单元测试

import java.text.ParseException;

@Test (expected=ParseException.class)
public void testConvertDate() {
    String date = "Tue 3434 20 23:33:44 EST 2014";
    MyDate mydate = new MyDate();
    Date result = instance.convertDate(date); //this line shows the message
}

方式

import java.text.ParseException;
public Date convertDate(String d) throws ParseException {
    ....
}

2 个答案:

答案 0 :(得分:2)

因为异常是checked exception,需要在try/catch块中声明或封闭。在方法级别声明它以允许它由JUnit管理。

@Test (expected=ParseException.class)
public void testConvertDate() throws ParseException {

答案 1 :(得分:0)

你的" convertDate(日期d)"方法必须抛出ParseException(确保它没有捕获它...) 然后它会传播到你期待它的Test方法。