7

If we do a

throw new ArgumentException("Cannot do that");

How do you Assert that this ArgumentException happened with Microsoft's Testing Framework?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Zachary Scott
  • 20,968
  • 35
  • 123
  • 205
  • Possible Duplicate [C#: How do I use Assert (Unit Testing) to verify that an exception has been thrown?](http://stackoverflow.com/q/933613/299327). – Ryan Gates Jan 25 '13 at 19:12

1 Answers1

13

You could decorate your unit test with the [ExpectedException] attribute:

[ExpectedException(typeof(ArgumentException))]
[TestMethod]
public void Foo()
{
    throw new ArgumentException("foo");
}

Don't ask though about asserting the exception message :-)

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thus why Unit tests shouldn't test more than one thing. What if you did a Try / Catch then processed the caught exception with an Assert? – Zachary Scott Jul 13 '10 at 17:31
  • 1
    Well, of course you could do that but in this case you will be writing, let me count, 7 more lines of code (probably a bit less if you put the `{` on the same line), and every line of code you write is hiding a potential error and decreasing the readability of the code, so why doing it when you can avoid it :-) – Darin Dimitrov Jul 13 '10 at 17:34