对于下面的方法,有没有办法创建单元测试来导致DatatypeConfigurationException,所以我可以测试它是否抛出ConversionException?
这是我的代码:
public static XMLGregorianCalendar getXMLGregorianCalendar(final LocalDate localDate) {
XMLGregorianCalendar xmlGregorianCalendar = null;
if (localDate != null) {
final String dateString = localDate.format(yyyMMddFormat);
try {
xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateString);
} catch (DatatypeConfigurationException e) {
throw new ConversionException("Unable to format LocalDate.", e);
}
}
return xmlGregorianCalendar;
}
Run Code Online (Sandbox Code Playgroud)
这里抛出的已检查异常javax.xml.datatype.DatatypeFactory.newInstance()。
它是一个静态方法。所以你不能直接嘲笑它。
1)作为替代方案,您可以尝试找到可能引发异常的场景。
我们走吧。异常在这里抛出:
private static <T> T findServiceProvider(final Class<T> type)
throws DatatypeConfigurationException{
try {
return AccessController.doPrivileged(new PrivilegedAction<T>() {
public T run() {
final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
final Iterator<T> iterator = serviceLoader.iterator();
if (iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
}
});
} catch(ServiceConfigurationError e) {
final DatatypeConfigurationException error =
new DatatypeConfigurationException(
"Provider for " + type + " cannot be found", e);
throw error;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,DatatypeConfigurationException当ServiceConfigurationError被抛出并被抓住时,也会被抛出。但这 ServiceConfigurationError是一个错误而不是例外。
尝试模拟错误变得非常棘手。
2)测试它的其他替代方法:包装 DatatypeFactory.newInstance()在您自己的类的实例中。
通过这种方式,你可以毫无困难地模拟它:
public class DataTypeFactoryWrapper {
public DatatypeFactory newInstance(){
return DatatypeFactory.newInstance();
}
}
Run Code Online (Sandbox Code Playgroud)
现在以这种方式更改您的代码:
private DataTypeFactoryWrapper dataTypeFactoryWrapper;
//...
xmlGregorianCalendar = dataTypeFactoryWrapper.newInstance().newXMLGregorianCalendar(dateString);
Run Code Online (Sandbox Code Playgroud)
现在您可以dataTypeFactoryWrapper在测试类中进行模拟。
3)最后一个选择:不要测试它。按原样考虑,它是一个Error包装器,并且Error很难/很难测试。
无论javadoc如何解释:
Error 是 Throwable 的子类,它指示合理的应用程序不应尝试捕获的严重问题。大多数此类错误都是异常情况
| 归档时间: |
|
| 查看次数: |
1594 次 |
| 最近记录: |