Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct syntax for NUnit Throws

Tags:

c#

.net

nunit

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

like image 372
user9993 Avatar asked Dec 16 '25 14:12

user9993


1 Answers

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>());
like image 131
stuartd Avatar answered Dec 19 '25 05:12

stuartd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!