2

I need to write a test that verifies that creating an object and passing in null arguments will throw a ArgumentNullException.

This is what I have:

[Test]
public void ThrowsOnNullDependency()
{
    Assert.Throws(() => new FileService(null), Throws.Exception.TypeOf<ArgumentNullException>());
}

And I'm getting the following exceptions. I've seen a few different sites and SO answers that all seem to use different features and syntax of NUnit. What is the correct way to check if something throws an exception or not with NUnit3?

CS1503 Argument 2: cannot convert from 'NUnit.Framework.Constraints.ExactTypeConstraint' to 'NUnit.Framework.TestDelegate'

CS1660 Cannot convert lambda expression to type 'IResolveConstraint' because it is not a delegate type

stuartd
  • 70,509
  • 14
  • 132
  • 163
user9993
  • 5,833
  • 11
  • 56
  • 117

1 Answers1

7

If you do just want to check that the exception is thrown, then either of these will work:

Assert.Throws<ArgumentNullException>(() => new FileService(null));

Assert.Throws(typeof(ArgumentNullException), () => new FileService(null));

If you do want to use the ThrowsConstraint for more control over the check, then the syntax would be this as you use Assert.That with the constraint:

Assert.That(() => new FileService(null), Throws.TypeOf<ArgumentNullException>());
stuartd
  • 70,509
  • 14
  • 132
  • 163