在设计为读取特定电子表格的应用程序中,假设它具有某些工作表,则有一种设计用于返回这些工作表的方法。这是使用Epplus库:
public ExcelWorksheet findExcelSheet(ExcelPackage spreadsheet, string v);
{
foreach (var sheet in spreadsheet.Workbook.Worksheets)
{
if ((sheet.Name).CompareTo(v)==0)
{
// matching sheet found
return sheet;
}
}
// at this point, the sheet has not been found
// we are assuming the user has supplied the correct spreadsheet, with the required worksheets
// if not, the program cannot continue, as it is totally dependent on this. It will not work with any old spreadsheet
throw new Exception("Could not find required Excel worksheet: " + v);
}
如代码中所述,其目的是检查带有所需名称的工作表是否存在,并将其作为ExcelWorksheet
对象返回。它们被调用了三次,因为有三个required工作表。
此方法需要通过Microsoft.VisualStudio.TestTools.UnitTesting
进行单元测试
public void findExcelSheet_Test()
{
// arrange
ExcelPackage testSpreadsheet = new ExcelPackage();
ExcelWorksheet testWsFPS = testSpreadsheet.Workbook.Worksheets.Add("FPS");
ExcelWorksheet testWsDRS = testSpreadsheet.Workbook.Worksheets.Add("DRS");
ExcelWorksheet testWsDPC = testSpreadsheet.Workbook.Worksheets.Add("DPC");
// act
// assert
}
上面的测试方法是一个起点。最好的方法是什么?
您几乎在那里。只需要抛出异常。但是,由于您使用的是Microsoft的测试工具,因此必须在预期的异常上将属性添加到单元测试中(其他测试套件,例如nunit或xunit都具有Assert.Throws ...):
[TestMethod]
[ExpectedException(typeof(Exception))]
public void findExcelSheet_Test()
{
// arrange
ExcelPackage testSpreadsheet = new ExcelPackage();
ExcelWorksheet testWsFPS = testSpreadsheet.Workbook.Worksheets.Add("FPS");
ExcelWorksheet testWsDRS = testSpreadsheet.Workbook.Worksheets.Add("DRS");
ExcelWorksheet testWsDPC = testSpreadsheet.Workbook.Worksheets.Add("DPC");
// act
findExcelSheet(testSpreadsheet, Path.GetRandomFileName()); //or some other random string
// assert
}