Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying ArgumentException and its message in Nunit , C#

In my test program in Nunit, I want to verify that it's getting the write Argument Exception by verifying the message.

    [Test]     public void ArgumentsWorkbookNameException()     {         const string workbookName = "Tester.xls";         var args = new[] { workbookName, "Sheet1", "Source3.csv", "Sheet2", "Source4.csv" };         Assert.Throws(typeof(ArgumentException), delegate { var appargs = new ApplicationArguments(args); }, "Invalid ending parameter of the workbook. Please use .xlsx");      } 

After testing this out, this doesn't work when I modified the message in the main program.

        int wbLength = args[0].Length;          // Telling the user to type in the correct workbook name file.         if (args[0].Substring(wbLength-5,5)!=".xlsx")         {             throw new ArgumentException(                 "Invalid ending parameter of the workbook. Please use .xlsx random random");         } 

The unit test still passed, regardless if I changed the message.

How do I do it? Or is there no such things in C#. My colleague said there are options like that in Ruby and RSPEC, but he's not 100% sure on C#.

like image 506
Henry Zhang Avatar asked Jul 23 '13 16:07

Henry Zhang


2 Answers

Use the fluent interface to create assertions:

Assert.That(() => new ApplicationArguments(args),      Throws.TypeOf<ArgumentException>()         .With.Message.EqualTo("Invalid ending parameter of the workbook. Please use .xlsx random random")); 
like image 129
PleasantD Avatar answered Oct 07 '22 14:10

PleasantD


I agree with Jon that "such tests are unnecessarily brittle". However, there are at least two ways to check for exception message:

1: Assert.Throws returns an exception, so you can make an assertion for its message:

var exception = Assert.Throws<ArgumentException>(() => new ApplicationArguments(args)); Assert.AreEqual("Invalid ending parameter of the workbook. Please use .xlsx random random", exception.Message); 

2: [HISTORICAL] Before NUnit 3, you could also use ExpectedException attribute. But, take a note that attribute waits for an exception in the whole tested code, not only in code which throws an exception you except. Thus, using this attribute is not recommended.

[Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Invalid ending parameter of the workbook. Please use .xlsx random random")] public void ArgumentsWorkbookNameException() {     const string workbookName = "Tester.xls";     var args = new[] { workbookName, "Sheet1", "Source3.csv", "Sheet2", "Source4.csv" };     new ApplicationArguments(args); } 
like image 29
Dariusz Woźniak Avatar answered Oct 07 '22 14:10

Dariusz Woźniak