所以,我正在做一个项目,我必须测试我的方法是否在 ParseException
发生时捕获它。这是我需要测试的方法的样子:
public void convertToModel(final BuildStone bs, final TextBuildStone model) {
try {
model.setBeginDateRange(ProjectDateConverter.projectDateToCalendarDefaultMin(bs.getFromDate(), true));
} catch (final ParseException e) {
SystemContext.getLogger().warning(
this,
"treatGeneralData",
"Date not converted: {0}, BeginDate set at MinDate",
bs.getFromDate());
model.setBeginDateRange(CalendarConstants.getMinDate());
}
所以我必须测试此方法何时捕获 ParseException
。
抛出 ParseException 的方法是 projectDateToCalendarDefaultMin
,这是该方法的代码:
public static Calendar projectDateToCalendarDefaultMin(final BigDecimal dateValue, final boolean useMinDate) throws ParseException {
return dateValue == null ? ProjectDateConverter.projectDateStringToCalendar(null, useMinDate, false) : ProjectDateConverter
.projectDateStringToCalendar(dateValue.toString(), useMinDate, false);
抛出 ParseException 的方法称为 projectDateStringToCalendar
。这是它的样子:
private static Calendar projectDateStringToCalendar(final String dateValue, final boolean useMinDate, final boolean useMaxDate)
throws ParseException {
if (useMinDate && useMaxDate) {
throw new IllegalArgumentException("useMinDate and useMaxDate may not be set as true ");
}
if (StringUtils.isEmpty(dateValue)) {
if (useMinDate) {
return CalendarConstants.getMinDate();
} else if (useMaxDate) {
return CalendarConstants.getMaxDate();
} else {
return null;
}
}
...
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime(new SimpleDateFormat("yyyyMMdd").parse(dateValue));
return gc;
}
所以这是最终在 parse()
方法中抛出 ParseException
的地方。 ParseException
来自 text.parse
包,解析方法如下所示:
public Date parse(String source) throws ParseException
{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException("Unparseable date: \"" + source + "\"" ,
pos.errorIndex);
return result;
}
我已经尝试做的是将 bs.getFromDate
设置为 null 但测试将始终为红色。我在测试中使用了 @Test(expected: ParseException.class)
注释,但我就是不能让它变绿。也许 bs.getFromDate
不是正在解析的正确值?
有没有人知道如何使这个测试起作用?提前致谢!
最佳答案
好的,最简单的方法是:
- 使用将抛出 ParseException 的参数调用您的方法
- 如果测试没有抛出异常,则意味着它在 方法
查看您的代码还有另一种方法:
如果捕获到异常,我看到您在模型上设置了开始日期范围:
model.setBeginDateRange(CalendarConstants.getMinDate());
因此在您的测试中您可以检查:
model.getBeginDateRange() 是否等于 CalendarConstants.getMinDate()
(根据代码的工作方式,您可能需要在检查之前获取模型的实际版本)
希望对您有所帮助。
关于java - JUnit 如何测试 ParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17132564/