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;
using System.Threading.Tasks;
namespace NUnit.Framework.Constraints
{
[NullableContext(1)]
[Nullable(0)]
public class ThrowsConstraint : PrefixConstraint
{
[Nullable(0)]
private sealed class ThrowsConstraintResult : ConstraintResult
{
[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);
}
}
[Nullable(2)]
private Exception _caughtException;
[Nullable(2)]
public Exception ActualException {
[NullableContext(2)]
get {
return _caughtException;
}
}
public override string Description => base.BaseConstraint.Description;
public ThrowsConstraint(IConstraint baseConstraint)
: base(baseConstraint, string.Empty)
{
}
public override ConstraintResult ApplyTo<[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<[Nullable(2)] TActual>(ActualValueDelegate<TActual> del)
{
return ApplyTo((Delegate)del);
}
[AsyncStateMachine(typeof(<ApplyToAsync>d__8<>))]
public override Task<ConstraintResult> ApplyToAsync<[Nullable(2)] TActual>(Func<Task<TActual>> actual)
{
<ApplyToAsync>d__8<TActual> stateMachine = default(<ApplyToAsync>d__8<TActual>);
stateMachine.<>t__builder = AsyncTaskMethodBuilder<ConstraintResult>.Create();
stateMachine.<>4__this = this;
stateMachine.actual = actual;
stateMachine.<>1__state = -1;
stateMachine.<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
}
}