Example:
Assert.AreEqual(**null**, Program.nDaysMonth(5, -10), "Error nDaysMonth, Month may -10.");
I expect a exception. How I can expect a exception in Assert.AreEqual?
Thanks.
Example:
Assert.AreEqual(**null**, Program.nDaysMonth(5, -10), "Error nDaysMonth, Month may -10.");
I expect a exception. How I can expect a exception in Assert.AreEqual?
Thanks.
You don't use Assert.AreEqual
, you use Assert.Throws
:
Assert.Throws<ArgumentOutOfRangeException>(() => Program.nDaysMonth(5, -10));
This checks that the correct exception is thrown. If you want to add more assertions, you can use the return value:
var exception = Assert.Throws<ArgumentOutOfRangeException>(...);
Assert.AreEqual("Foo", exception.Message); // Or whatever
This works in at least NUnit and xUnit; if you're using a different testing framework you should look for similar functionality. If it doesn't exist, I'd recommend implementing it yourself - it's easy enough to do, and much cleaner than the alternatives (a try/catch block, or a method-wide ExpectedException
attribute). Alternatively, change unit test framework if you can...
I'd also strongly advise you to start following the normal .NET naming conventions - nDaysMonth
is not a good method name...
Some frameworks support decorating the method with an [ExpectedException]
attribute - I would recommend against using that:
If you are using the Microsoft test framework, you would need to decorate the method with the ExpectedExceptionAttribute:
[TestClass]
public class UnitTest1
{
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TestMethod1()
{
//Do whatever causes the exception here
}
}
The test will then pass or fail depending on the exception being thrown or not.
However, as Jon notes below, please find a test framework that supports Assert.Throws
or some variation there-of. Decorating with the expected exception can cause false passes or other issues in code depending on what you are doing, and it makes it difficult to do anything after the exception is thrown in the method. Using a full-featured framework will improve the quality of your tests dramatically.
I recommend NUnit, http://www.nunit.org/
Or there are others like XUnit https://github.com/xunit/xunit
or literally dozens of others: http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#.NET_programming_languages