Search code examples
c#.netunit-testingexceptionepplus

Check if exception thrown (and correct exception) with Microsoft testing tools


Consider a method which returns an ExcelWorksheet from an ExcelPackage (with the Epplus library):

public ExcelWorksheet findExcelSheet(ExcelPackage spreadsheet, string v)

This method throws an Exception if a worksheet is not found within the spreadsheet whose name is "v".

A unit test is written for this method:

[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
}

How, with Microsoft.VisualStudio.TestTools.UnitTesting, can it be tested for when it throws the exceptions, and that they are the correct type of exception?


Solution

  • You need to use [MSTest V2] to be able to Assert.ThrowsException

    Starting with VS2017, the in-box Unit Test Project templates use only MSTest V2.

    • Install package MSTest.TestFramework from Nuget
    • Install package MSTest.TestAdapter from Nuget
    • Then you can use Assert.ThrowsException<ArgumentOutOfRangeException>..
     //Substitute `ArgumentOutOfRangeException` with the exception that you receive
     Assert.ThrowsException<ArgumentOutOfRangeException>( ()=>FindExcelSheet(spreadsheet,""));