Search code examples
c#.netnunit

Using NUnit to test for any type of exception


I have a class that creates a file.

I am now doing integration tests to make sure the class is ok.

I am passing in invalid directory and file names to make sure exceptions are thrown.

In my tests are I am using:

[Test]
public void CreateFile_InvalidFileName_ThrowsException()
{
    //Arrange
    var logger = SetupLogger("?\\");

    //Act

    //Assert
    Assert.Throws<Exception>(()=> logger.CreateFile());
 }

However in this scenario the test is failing as an ArgumentException is thrown. I thought by adding just Exception it would pass.

Is there a way to make this pass just using Exception?


Solution

  • The help for Assert.Throws<> states that it "Verifies a delegate throws a particular type of exception when called"

    Try the Assert.That version as it will catch any Exception:

    private class Thrower
    {
        public void ThrowAE() { throw new ArgumentException(); }
    }
    
    [Test]
    public void ThrowETest()
    {
        var t = new Thrower();
        Assert.That(() => t.ThrowAE(), Throws.Exception);
    }