0

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Al2110
  • 566
  • 9
  • 25
  • Does this answer your question? [How do I use Assert to verify that an exception has been thrown?](https://stackoverflow.com/questions/933613/how-do-i-use-assert-to-verify-that-an-exception-has-been-thrown) – Scircia Feb 25 '20 at 06:09
  • @Clint I will check if it works tomorrow, but it looks fine. – Al2110 Feb 25 '20 at 10:03

1 Answers1

3

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,""));
Clint
  • 6,011
  • 1
  • 21
  • 28