Search code examples
c#unit-testingexceptionnunitassert

Use NUnit Assert.Throws method or ExpectedException attribute?


I have discovered that these seem to be the two main ways of testing for exceptions:

Assert.Throws<Exception>(()=>MethodThatThrows());

[ExpectedException(typeof(Exception))]

Which of these would be best? Does one offer advantages over the other? Or is it simply a matter of personal preference?


Solution

  • The first allows you to test for more than one exception, with multiple calls:

    Assert.Throws(()=>MethodThatThrows());
    Assert.Throws(()=>Method2ThatThrows());
    

    The second only allows you to test for one exception per test function.