我需要使用Junit
抽象类中的一些异常进行测试。抽象类Java中的模拟异常
抽象类:
public abstract class AbstractReport {
private final Log logger = LogFactory.getLog(this.getClass());
private static final String PREFIX_NAME = "reportFile";
protected Path generate(String templatePath, Map<String, Object> params, JRDataSource datasource) {
// Temporal file to write the document
Path file = null;
try {
file = Files.createTempFile(PREFIX_NAME, null);
} catch (final IOException e) {
logger.error("Exception creating temp file",e);
return null;
}
try (InputStream reportStream = this.getClass().getResourceAsStream(templatePath); FileOutputStream outputStream = new FileOutputStream(file.toFile())) {
final JasperDesign jd = JRXmlLoader.load(reportStream);
final JasperReport jr = JasperCompileManager.compileReport(jd);
final JasperPrint jp = JasperFillManager.fillReport(jr, params, datasource);
final JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(SimpleExporterInput.getInstance(Arrays.asList(jp)));
final SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
exporter.setConfiguration(configuration);
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
exporter.exportReport();
} catch (final JRException e) {
logger.error("Exception processing report",e);
file.toFile().delete();
return null;
} catch (final FileNotFoundException e) {
logger.error("Report template not found",e);
file.toFile().delete();
return null;
} catch (final IOException e) {
logger.error("Exception reading report template",e);
file.toFile().delete();
return null;
}
return file;
}
}
我需要从这个代码测试每捕获。研究我发现Mockito你可以在调用方法时模拟异常,所以例如当我调用“generate”时我可以触发异常,但是,我不知道如何在我的“生成”代码中触发异常(例如创建临时文件时的IOException
)。
如果这个类没有依赖关系,那就没有什么可以模拟的。 –