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

ThrowsConstraint

ThrowsConstraint is used to test the exception thrown by a delegate by applying a constraint to it.
using NUnit.Framework.Internal; using System; using System.Runtime.CompilerServices; namespace NUnit.Framework.Constraints { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public class ThrowsConstraint : PrefixConstraint { [System.Runtime.CompilerServices.Nullable(0)] private sealed class ThrowsConstraintResult : ConstraintResult { [System.Runtime.CompilerServices.Nullable(2)] private readonly ConstraintResult _baseResult; public ThrowsConstraintResult(ThrowsConstraint constraint) : base(constraint, null) { base.Status = ConstraintStatus.Failure; } public ThrowsConstraintResult(ThrowsConstraint constraint, Exception caughtException, ConstraintResult baseResult) : base(constraint, caughtException) { if (baseResult.IsSuccess) base.Status = ConstraintStatus.Success; else base.Status = ConstraintStatus.Failure; _baseResult = baseResult; } public override void WriteActualValueTo(MessageWriter writer) { if (_baseResult == null) writer.Write("no exception thrown"); else _baseResult.WriteActualValueTo(writer); } } [System.Runtime.CompilerServices.Nullable(2)] private Exception _caughtException; [System.Runtime.CompilerServices.Nullable(2)] public Exception ActualException { [System.Runtime.CompilerServices.NullableContext(2)] get { return _caughtException; } } public override string Description => base.BaseConstraint.Description; public ThrowsConstraint(IConstraint baseConstraint) : base(baseConstraint, string.Empty) { } public override ConstraintResult ApplyTo<[System.Runtime.CompilerServices.Nullable(2)] TActual>(TActual actual) { Delegate parameterlessDelegate = ConstraintUtils.RequireActual<Delegate>(actual, "actual", false); _caughtException = ExceptionHelper.RecordException(parameterlessDelegate, "actual"); if (_caughtException != null) return new ThrowsConstraintResult(this, _caughtException, base.BaseConstraint.ApplyTo(_caughtException)); return new ThrowsConstraintResult(this); } public override ConstraintResult ApplyTo<[System.Runtime.CompilerServices.Nullable(2)] TActual>(ActualValueDelegate<TActual> del) { return ApplyTo((Delegate)del); } } }