我需要使用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
)。
如果這個類沒有依賴關係,那就沒有什麼可以模擬的。 –