Use NUnit Assert.Throws method or ExpectedException attribute?

C#Unit TestingExceptionNunitAssert

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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");

    }

Solution 4 - C#

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

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

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamuelDavisView Question on Stackoverflow
Solution 1 - C#Alexander StepaniukView Answer on Stackoverflow
Solution 2 - C#chue xView Answer on Stackoverflow
Solution 3 - C#Mike ParkhillView Answer on Stackoverflow
Solution 4 - C#Reverend SfinksView Answer on Stackoverflow
Solution 5 - C#Gireesh kView Answer on Stackoverflow