170

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?

3
  • 4
    A 3rd option is the fluent style: Assert.That(() => MethodThatThrows(), Throws.Exception) Commented Oct 7, 2016 at 2:37
  • 4
    NUnit version 3 and later no longer support the ExpectedException attribute, so for version 3+ only the Assert.Throws variant is relevant.
    – joanlofe
    Commented Sep 18, 2018 at 13:34
  • Why is it so? That Nunit3 decided to drop that support? Was googling around and could not find explanation for it... JUnit still supports this way, doesn't it?
    – ahaaman
    Commented Aug 6, 2019 at 12:43

5 Answers 5

275

The main difference is:

ExpectedException() attribute makes test passed if exception occurs in any place in the test method.
The usage of Assert.Throws() allows to specify exact place of the code where exception is expected.

NUnit 3.0 drops official support for ExpectedException altogether.

So, I definitely prefer to use Assert.Throws() method rather than ExpectedException() attribute.

4
  • 8
    This is by far the correct answer. Incidentally, Assert.Throws() also returns the exception, which can allow additional inspection of the properties of the exception, if they matter to you. Commented May 29, 2015 at 18:14
  • 1
    Finally answer why I can't get ExpectedException to work .. with version 3.
    – JanT
    Commented Mar 20, 2017 at 21:46
  • 3
    Here is the link github.com/nunit/docs/wiki/Breaking-Changes - ExpectedExceptionAttribute no longer supported. Commented Dec 18, 2017 at 16:54
  • To change this to work under NUnit 3.0, change it to the following Commented Feb 2, 2019 at 17:27
110

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.

3
  • 27
    A test should only test one distinct bit of logic, so wouldn't testing two errors in the same unit test be considered bad practice? Commented Feb 22, 2013 at 0:03
  • 6
    @SamuelDavis - in general you wouldn't want to test different cases in the same test. However, there may be some use case for multiple Assert.Throws.
    – chue x
    Commented Feb 22, 2013 at 0:11
  • 3
    Either way, here you get the exception as a parameter, which allows you to assert details in the exception. Also, using "Expected exception" does not protect you for the same exception type being thrown in another method call. Here, you target the exact method and not the whole test. Even though your test should call very little code, you're never too safe. Especially when code becomes complex and/or exception too generic. Stuff like "ArgumentNullExceptions" can be thrown a lot and would for example be easily missed using the ExpectedException. Assert.Throws would not miss it.
    – Gil Sand
    Commented Jun 2, 2016 at 21:51
52

I prefer Assert.Throws() since it allows me to verify and assert other conditions after the exception is thrown.

[Test]
[Category("Slow")]
public void IsValidLogFileName_nullFileName_ThrowsExcpetion()
{
    var a = new MyTestObject();

    // the exception we expect thrown from the IsValidFileName method
    var ex = Assert.Throws<ArgumentNullException>(() => a.IsValidLogFileName(""));

    // now we can test the exception itself
    Assert.That(ex.Message == "Blah");
}
4
  • This is one of the better answers, it's pretty common that you want to verify that something has entered an errored state after the exception is thrown. Commented Apr 1, 2016 at 5:47
  • Good answer! But what's the meaning of [Category("Slow")] and a?
    – themefield
    Commented Aug 12, 2020 at 0:39
  • You can use Categories to group your tests - it's not needed for this example - in this case "Slow" might mean that want to be able to choose whether or not to run "slow" tests every time or only as part of nightly or weekly runs or something. I believe the "a" was a syntax error technically, but it's just the object that you're testing. Commented Aug 18, 2020 at 20:11
  • 1
    (+1) Being able to test the exception itself after the Assert.Throws is useful especially with AggregateException and its InnerExceptions collection. Commented Jan 24, 2023 at 11:51
13

You may also strong type the error you're expecting (like the old attrib version).

Assert.Throws<System.InvalidOperationException>(() => breakingAction())
1

If you are using older version(<=2.0) of NUnit then you need to use ExpectedException.

If you are using 2.5 or later version then you can use Assert.Throw()

https://github.com/nunit/docs/wiki/Breaking-Changes

How to use: https://www.nunit.org/index.php?p=exceptionAsserts&r=2.5

Not the answer you're looking for? Browse other questions tagged or ask your own question.