C# How I can expect a exception in Assert.AreEqual?

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.

Jon Skeet
people
quotationmark

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:

  1. That makes the test unclear about where you expect the exception to be thrown.
  2. If the exception is thrown elsewhere in the test method (i.e. your code is broken) the test will still pass.
  3. You can't do anything else after the exception is thrown.
  4. You can't check anything else about the exception.

people

See more on this question at Stackoverflow