因此,我正在处理一个项目,我必须测试我的方法在发生时是否捕获到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不是正在解析的正确值?
有没有人知道如何让这个测试工作?提前感谢!
发布于 2013-06-16 20:44:26
好的,最简单的方法是:
使用将抛出ParseException
中捕获的
查看您的代码,您可以使用另一种方法:
如果捕获到异常,我看到您在模型上设置了开始日期范围:model.setBeginDateRange(CalendarConstants.getMinDate());
所以在你的测试中,你可以检查:
model.getBeginDateRange()等于CalendarConstants.getMinDate()
(在进行检查之前,您可能需要获取模型的实际版本,这取决于代码的工作方式)
希望这能有所帮助。
发布于 2013-06-16 19:02:33
JUnit @Test(expected)批注要求您准确地知道将引发哪个异常。
如果假设抛出了ParseException,但抛出了NullPointerException,则测试将显示为失败。
尝试使用@Test(expected = Exception.class),看看是否可以处理所有这些问题。
发布于 2013-06-16 19:03:27
使用模拟框架(例如Mockito、EasyMock)模拟对projectDateToCalendarDefaultMin方法的调用并抛出ParseException。
您的post条件断言将是模型的beginDateRange属性已设置为CalendarConstants.getMinDate()。
https://stackoverflow.com/questions/17132564
复制相似问题