旨在查找电子表格中特定工作表的单元测试方法

Unit testing method designed to find specific worksheets in spreadsheet

在设计用于读取特定电子表格的应用程序中,假定具有某些工作表,有一种方法旨在 return 这些工作表。这是使用 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);
}

如代码中所述,其目的是检查工作表是否存在所需名称,并且 return 它们作为 ExcelWorksheet 对象。它们被调用了三次,因为有三个 需要 个工作表。

此方法需要使用 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

}