<PackageReference Include="NUnit" Version="3.7.1" />

ThrowsExceptionConstraint

ThrowsExceptionConstraint tests that an exception has been thrown, without any further tests.
using System; namespace NUnit.Framework.Constraints { public class ThrowsExceptionConstraint : Constraint { private class ThrowsExceptionConstraintResult : ConstraintResult { public ThrowsExceptionConstraintResult(ThrowsExceptionConstraint constraint, Exception caughtException) : base(constraint, caughtException, caughtException != null) { } public override void WriteActualValueTo(MessageWriter writer) { if (base.Status == ConstraintStatus.Failure) writer.Write("no exception thrown"); else base.WriteActualValueTo(writer); } } public override string Description => "an exception to be thrown"; public override ConstraintResult ApplyTo<TActual>(TActual actual) { TestDelegate testDelegate = actual as TestDelegate; Exception caughtException = null; if (testDelegate == null) throw new ArgumentException($"""{actual.GetType().Name}", "actual"); try { testDelegate(); } catch (Exception ex) { caughtException = ex; } return new ThrowsExceptionConstraintResult(this, caughtException); } protected override object GetTestObject<TActual>(ActualValueDelegate<TActual> del) { return (TestDelegate)delegate { del(); }; } } }