【问题标题】:Check if exception thrown (and correct exception) with Microsoft testing tools使用 Microsoft 测试工具检查是否抛出异常(并纠正异常)
【发布时间】:2020-06-08 19:41:59
【问题描述】:

考虑一个从ExcelPackage(使用 Epplus 库)返回 ExcelWorksheet 的方法:

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 测试它何时抛出异常,以及它们是否是正确的异常类型?

【问题讨论】:

标签: c# .net unit-testing exception epplus


【解决方案1】:

您需要使用 [MSTest V2] 才能 Assert.ThrowsException

从 VS2017 开始,内置单元测试项目模板仅使用 MSTest V2。

  • 从 Nuget 安装包 MSTest.TestFramework
  • 从 Nuget 安装包 MSTest.TestAdapter
  • 然后你可以使用Assert.ThrowsException<ArgumentOutOfRangeException>..
 //Substitute `ArgumentOutOfRangeException` with the exception that you receive
 Assert.ThrowsException<ArgumentOutOfRangeException>( ()=>FindExcelSheet(spreadsheet,""));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2020-08-18
    • 2013-08-23
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多