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#.
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"));
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With