包含switch case语句和insert to db的方法的单元测试



我有一个方法,它包含一个开关用例块,该块遍历excel文件以获得要写入数据库的值。我需要为这个方法写一个单元测试,但我不知道从哪里开始
下面是我需要编写单元测试的方法。如果有人能给我建议,我将不胜感激。

public void loadAccount() throws Exception {
Connection conn = null;
PreparedStatement insert = null;
Properties props = new Properties();
try {
conn = connMan.allocateConnection();
conn.setAutoCommit(false);
insert = conn.prepareStatement(INSERT_SQL_TOP_ACCOUNTS);
FileInputStream inputStream = new FileInputStream("path");
props.load(inputStream);
String excelFilePath = props.getProperty("Account");
FileInputStream iStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(iStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
// Current date for entry into db
java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
insert.setDate(1, sqlDate);
// Skips the header row
iterator.next();
// Iterate through the first sheet and get the cell values
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int columnIndex = cell.getColumnIndex();
switch (columnIndex) {
case 0:
String institution = cell.getStringCellValue();
insert.setString(2, institution);
break;
case 1:
// Formatting data because of alphanumeric mix in row
DataFormatter formatter = new DataFormatter();
String dept = formatter.formatCellValue(cell);
insert.setString(3, dept);
break;
case 2:
int hits = (int) cell.getNumericCellValue();
insert.setInt(4, hits);
break;
case 3:
int visitors = (int) cell.getNumericCellValue();
insert.setInt(5, visitors);
break;
}
}
insert.addBatch();
}
int[] insertCount = insert.executeBatch();
int successInserted = 0;
for (int item : insertCount) {
if (item == 1) {
successInserted++;
}
}
log.info("There're " + insertCount.length + " need to be inserted, with successfully [" + successInserted
+ "] inserted");
conn.commit();          
} catch (Exception e) {
log.error("Exception in loadAccount:" + e);
try {
conn.rollback();
} catch (SQLException e1) {
log.error("Exception when rollback the loading.", e1);
throw e1;
}
throw e;
} finally {
connMan.closeStatement(insert);
try {
if (conn != null) {
connMan.deallocateConnection(conn);
}
} catch (SQLException e) {
log.error("Exception in loadAccount:" + e);
throw e;
}
}
}

首先,为了简化测试,您应该确保(就像在"重构到"中一样(您的方法只做一件事(读取excel文件、提取值和写入数据库至少是三件事(。走测试驱动的开发之路,首先会留下这些单独的方法。

然后,您应该获取您喜欢的mocking框架并模拟数据库访问,因为使用真正的数据库将是一个集成测试,而不是单元测试。

之后,你应该逐一测试你的新方法。最好添加一个"主谋",它可以方便地调用其他方法并收集结果,这样你就可以在不调用其他方法的情况下测试你的方法。使用固定值(最好是边缘和错误情况(调用方法,并使用首选的单元测试框架来断言返回。

最新更新