考虑一个从ExcelWorksheet
(使用Epplus库)返回ExcelPackage
的方法:
public ExcelWorksheet findExcelSheet(ExcelPackage spreadsheet, string v)
如果在名称为“ v”的电子表格中找不到工作表,则此方法将引发Exception
。
为此方法编写了单元测试:
[TestMethod]
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
}
如何使用Microsoft.VisualStudio.TestTools.UnitTesting
在抛出异常时对其进行测试,并且它们是正确的异常类型?
从Nuget安装软件包MSTest.TestFramework
MSTest.TestAdapter
Assert.ThrowsException<ArgumentOutOfRangeException>..
//Substitute `ArgumentOutOfRangeException` with the exception that you receive
Assert.ThrowsException<ArgumentOutOfRangeException>( ()=>FindExcelSheet(spreadsheet,""));