Search code examples
c#json.netunit-testingnunit

How to Assert that a specific Exception is not thrown in NUnit?


I'm using NUnit for testing and have a piece of code where I use JObject.Parse(json). I want to ensure that this code does not throw a JsonReaderException. Here is the assertion I've tried:

Assert.That(() => { JObject.Parse(json); }, Throws.Nothing);

The above assertion only confirms that no exception is thrown, but I want to specifically assert that a JsonReaderException is not thrown. Is there a way to do this in NUnit?

I've tried using things like Throws.Not.JsonReaderException, among other things, but none seem to work. I expected to find an NUnit assertion that allows me to check for the absence of a specific exception, but couldn't find a way to do this.


Solution

  • Just negate the constraint with !:

    // Fails:
    Assert.That(() => { throw new AggregateException();},
        !Throws.InstanceOf<AggregateException>());
    
    // Passes:
    Assert.That(() => { throw new AggregateException();},
        !Throws.InstanceOf<InvalidOperationException>());
    

    Constraint class has overloaded ! operator which is somewhat equivalent to creating new NotConstraint. For example the following in this case will also work:

    Assert.That(() => { throw new AggregateException();},
        new NotConstraint(Throws.InstanceOf<InvalidOperationException>()));
    

    Note that current implementation of the operator is a bit more complex:

    public static Constraint operator !(Constraint constraint)
    {
        var r = (IResolveConstraint)constraint;
        return new NotConstraint(r.Resolve());
    }