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

Assert

public abstract class Assert : AssertBase
The Assert class contains a collection of static methods that implement the most common assertions used in NUnit.
using NUnit.Framework.Constraints; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace NUnit.Framework { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public abstract class Assert : AssertBase { [System.Runtime.CompilerServices.NullableContext(0)] private sealed class AssertionScope : IDisposable { [System.Runtime.CompilerServices.Nullable(1)] private readonly TestExecutionContext _context; private readonly int _assertionCountWhenEnteringScope; private readonly int _multipleAssertLevelInScope; private int _isDisposed; public AssertionScope() { _context = TestExecutionContext.CurrentContext; Guard.OperationValid(_context != null, "There is no current test execution context."); _assertionCountWhenEnteringScope = _context.CurrentResult.AssertionResults.Count; _multipleAssertLevelInScope = ++_context.MultipleAssertLevel; } public void Dispose() { if (Interlocked.Exchange(ref _isDisposed, 1) != 1) { if (TestExecutionContext.CurrentContext != _context || _context.MultipleAssertLevel != _multipleAssertLevelInScope) throw new InvalidOperationException("The assertion scope was disposed out of order."); _context.MultipleAssertLevel--; TestExecutionContext context = _context; if (context != null && context.MultipleAssertLevel == 0) { TestResult currentResult = context.CurrentResult; if (currentResult != null && currentResult.PendingFailures > 0) { _context.CurrentResult.RecordTestCompletion(); if (_context.CurrentResult.AssertionResults.Count > _assertionCountWhenEnteringScope) throw new MultipleAssertException(_context.CurrentResult); } } } } } private const string CharlieAppreciation = "Charlie Poole led NUnit for 20+ years, across at least 207 releases in 37 different repositories, authoring 4,898 commits across them. He participated in 2,990 issues, 1,305 PRs, and impacted 6,992,983 lines of code. NUnit was downloaded from NuGet 225+ million times during his tenure. And those numbers don't include at least 9 additional years of his work. This assertion attempts to pay homage to Charlie, who by virtue of his contributions has helped untold millions of tests pass."; private static readonly StackFilter SystemEnvironmentFilter = new StackFilter(" System\\.Environment\\."); internal const string IsTrueExpression = "Is.True"; [EditorBrowsable(EditorBrowsableState.Never)] public new static bool Equals(object a, object b) { throw new InvalidOperationException("Assert.Equals should not be used. Use Assert.AreEqual instead."); } [EditorBrowsable(EditorBrowsableState.Never)] public new static void ReferenceEquals(object a, object b) { throw new InvalidOperationException("Assert.ReferenceEquals should not be used. Use Assert.AreSame instead."); } [DoesNotReturn] public static void Charlie() { Pass("Charlie Poole led NUnit for 20+ years, across at least 207 releases in 37 different repositories, authoring 4,898 commits across them. He participated in 2,990 issues, 1,305 PRs, and impacted 6,992,983 lines of code. NUnit was downloaded from NuGet 225+ million times during his tenure. And those numbers don't include at least 9 additional years of his work. This assertion attempts to pay homage to Charlie, who by virtue of his contributions has helped untold millions of tests pass."); } [DoesNotReturn] public static void Pass(string message) { if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0) throw new Exception("Assert.Pass may not be used in a multiple assertion block."); throw new SuccessException(message); } [DoesNotReturn] public static void Pass() { Pass(string.Empty); } public static void Fail(string message) { ReportFailure(message); } public static void Fail() { Fail(string.Empty); } public static void Warn(string message) { IssueWarning(message); } [DoesNotReturn] public static void Ignore(string message) { if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0) throw new Exception("Assert.Ignore may not be used in a multiple assertion block."); throw new IgnoreException(message); } [DoesNotReturn] public static void Ignore() { Ignore(string.Empty); } [DoesNotReturn] public static void Inconclusive(string message) { if (TestExecutionContext.CurrentContext.MultipleAssertLevel > 0) throw new Exception("Assert.Inconclusive may not be used in a multiple assertion block."); throw new InconclusiveException(message); } [DoesNotReturn] public static void Inconclusive() { Inconclusive(string.Empty); } public static void Multiple(TestDelegate testDelegate) { using (EnterMultipleScope()) testDelegate(); } public static void Multiple(AsyncTestDelegate testDelegate) { using (EnterMultipleScope()) AsyncToSyncAdapter.Await(TestExecutionContext.CurrentContext, testDelegate.Invoke); } [AsyncStateMachine(typeof(<MultipleAsync>d__15))] public static Task MultipleAsync(AsyncTestDelegate testDelegate) { <MultipleAsync>d__15 stateMachine = default(<MultipleAsync>d__15); stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create(); stateMachine.testDelegate = testDelegate; stateMachine.<>1__state = -1; stateMachine.<>t__builder.Start(ref stateMachine); return stateMachine.<>t__builder.Task; } public static IDisposable EnterMultipleScope() { return new AssertionScope(); } internal static string ExtendedMessage(string methodName, string message, string actualExpression, string constraintExpression) { DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(4, 3); defaultInterpolatedStringHandler.AppendFormatted(methodName); defaultInterpolatedStringHandler.AppendLiteral("("); defaultInterpolatedStringHandler.AppendFormatted(actualExpression); defaultInterpolatedStringHandler.AppendLiteral(", "); defaultInterpolatedStringHandler.AppendFormatted(constraintExpression); defaultInterpolatedStringHandler.AppendLiteral(")"); string text = defaultInterpolatedStringHandler.ToStringAndClear(); return string.IsNullOrEmpty(message) ? text : (message + "\n" + text); } private static void ReportFailure(string message) { TestResult currentResult = TestExecutionContext.CurrentContext.CurrentResult; currentResult.RecordAssertion(AssertionStatus.Failed, message, GetStackTrace()); currentResult.RecordTestCompletion(); if (TestExecutionContext.CurrentContext.MultipleAssertLevel == 0) throw new AssertionException(currentResult.Message); if (TestExecutionContext.CurrentContext.ThrowOnEachFailureUnderDebugger && Debugger.IsAttached) try { throw new AssertionException(currentResult.Message); } catch (AssertionException) { } } private static void IssueWarning(string message) { TestResult currentResult = TestExecutionContext.CurrentContext.CurrentResult; currentResult.RecordAssertion(AssertionStatus.Warning, message, GetStackTrace()); } [System.Runtime.CompilerServices.NullableContext(2)] private static string GetStackTrace() { return StackFilter.DefaultFilter.Filter(SystemEnvironmentFilter.Filter(GetEnvironmentStackTraceWithoutThrowing())); } private static string GetEnvironmentStackTraceWithoutThrowing() { try { return Environment.StackTrace; } catch (Exception ex) { return ex.GetType().Name + " was thrown by the Environment.StackTrace property."; } } private static void IncrementAssertCount() { TestExecutionContext.CurrentContext.IncrementAssertCount(); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { Exception ex = null; try { AsyncToSyncAdapter.Await(TestExecutionContext.CurrentContext, code.Invoke); } catch (Exception ex2) { ex = ex2; } That(ex, expression, () => AssertBase.ConvertMessageWithArgs(message, args), "caughtException", "expression"); return ex; } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code) { return ThrowsAsync(expression, code, string.Empty, null); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code) { return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null); } [return: System.Runtime.CompilerServices.Nullable(2)] public static TActual ThrowsAsync<[System.Runtime.CompilerServices.Nullable(0)] TActual>(AsyncTestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) where TActual : Exception { return (TActual)ThrowsAsync(typeof(TActual), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static TActual ThrowsAsync<[System.Runtime.CompilerServices.Nullable(0)] TActual>(AsyncTestDelegate code) where TActual : Exception { return ThrowsAsync<TActual>(code, string.Empty, null); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception CatchAsync(AsyncTestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception CatchAsync(AsyncTestDelegate code) { return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception CatchAsync(Type expectedExceptionType, AsyncTestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception CatchAsync(Type expectedExceptionType, AsyncTestDelegate code) { return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code); } [return: System.Runtime.CompilerServices.Nullable(2)] public static TActual CatchAsync<[System.Runtime.CompilerServices.Nullable(0)] TActual>(AsyncTestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) where TActual : Exception { return (TActual)ThrowsAsync(new InstanceOfTypeConstraint(typeof(TActual)), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static TActual CatchAsync<[System.Runtime.CompilerServices.Nullable(0)] TActual>(AsyncTestDelegate code) where TActual : Exception { return (TActual)ThrowsAsync(new InstanceOfTypeConstraint(typeof(TActual)), code); } public static void DoesNotThrowAsync(AsyncTestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { That(code, new ThrowsNothingConstraint(), () => AssertBase.ConvertMessageWithArgs(message, args), "code", "new ThrowsNothingConstraint()"); } public static void DoesNotThrowAsync(AsyncTestDelegate code) { DoesNotThrowAsync(code, string.Empty, null); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception Throws(IResolveConstraint expression, TestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { Exception ex = null; Guard.ArgumentNotAsyncVoid(code, "code"); using (new TestExecutionContext.IsolatedContext()) try { code(); } catch (Exception ex2) { ex = ex2; } That(ex, expression, () => AssertBase.ConvertMessageWithArgs(message, args), "caughtException", "expression"); return ex; } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception Throws(IResolveConstraint expression, TestDelegate code) { return Throws(expression, code, string.Empty, null); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception Throws(Type expectedExceptionType, TestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception Throws(Type expectedExceptionType, TestDelegate code) { return Throws(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null); } [return: System.Runtime.CompilerServices.Nullable(2)] public static TActual Throws<[System.Runtime.CompilerServices.Nullable(0)] TActual>(TestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) where TActual : Exception { return (TActual)Throws(typeof(TActual), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static TActual Throws<[System.Runtime.CompilerServices.Nullable(0)] TActual>(TestDelegate code) where TActual : Exception { return Throws<TActual>(code, string.Empty, null); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception Catch(TestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception Catch(TestDelegate code) { return Throws(new InstanceOfTypeConstraint(typeof(Exception)), code); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception Catch(Type expectedExceptionType, TestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static Exception Catch(Type expectedExceptionType, TestDelegate code) { return Throws(new InstanceOfTypeConstraint(expectedExceptionType), code); } [return: System.Runtime.CompilerServices.Nullable(2)] public static TActual Catch<[System.Runtime.CompilerServices.Nullable(0)] TActual>(TestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) where TActual : Exception { return (TActual)Throws(new InstanceOfTypeConstraint(typeof(TActual)), code, message, args); } [return: System.Runtime.CompilerServices.Nullable(2)] public static TActual Catch<[System.Runtime.CompilerServices.Nullable(0)] TActual>(TestDelegate code) where TActual : Exception { return (TActual)Throws(new InstanceOfTypeConstraint(typeof(TActual)), code); } public static void DoesNotThrow(TestDelegate code, string message, [System.Runtime.CompilerServices.Nullable(2)] params object[] args) { That(code, new ThrowsNothingConstraint(), () => AssertBase.ConvertMessageWithArgs(message, args), "code", "new ThrowsNothingConstraint()"); } public static void DoesNotThrow(TestDelegate code) { DoesNotThrow(code, string.Empty, null); } public static void That(bool condition, NUnitString message = default(NUnitString), [CallerArgumentExpression("condition")] string actualExpression = "") { That(condition, Is.True, message, actualExpression, "Is.True"); } public static void That(bool condition, FormattableString message, [CallerArgumentExpression("condition")] string actualExpression = "") { That(condition, Is.True, message, actualExpression, "Is.True"); } public static void That(bool condition, Func<string> getExceptionMessage, [CallerArgumentExpression("condition")] string actualExpression = "") { That(condition, Is.True, getExceptionMessage, actualExpression, "Is.True"); } public static void That(Func<bool> condition, NUnitString message = default(NUnitString), [CallerArgumentExpression("condition")] string actualExpression = "") { That(condition(), Is.True, message, actualExpression, "Is.True"); } public static void That(Func<bool> condition, FormattableString message, [CallerArgumentExpression("condition")] string actualExpression = "") { That(condition(), Is.True, message, actualExpression, "Is.True"); } public static void That(Func<bool> condition, Func<string> getExceptionMessage, [CallerArgumentExpression("condition")] string actualExpression = "") { That(condition(), Is.True, getExceptionMessage, actualExpression, "Is.True"); } public static void That<[System.Runtime.CompilerServices.Nullable(2)] TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, NUnitString message = default(NUnitString), [CallerArgumentExpression("del")] string actualExpression = "", [CallerArgumentExpression("expr")] string constraintExpression = "") { IConstraint constraint = expr.Resolve(); IncrementAssertCount(); ConstraintResult constraintResult = constraint.ApplyTo(del); if (!constraintResult.IsSuccess) ReportFailure(constraintResult, message.ToString(), actualExpression, constraintExpression); } public static void That<[System.Runtime.CompilerServices.Nullable(2)] TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, FormattableString message, [CallerArgumentExpression("del")] string actualExpression = "", [CallerArgumentExpression("expr")] string constraintExpression = "") { IConstraint constraint = expr.Resolve(); IncrementAssertCount(); ConstraintResult constraintResult = constraint.ApplyTo(del); if (!constraintResult.IsSuccess) ReportFailure(constraintResult, message.ToString(), actualExpression, constraintExpression); } public static void That<[System.Runtime.CompilerServices.Nullable(2)] TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, Func<string> getExceptionMessage, [CallerArgumentExpression("del")] string actualExpression = "", [CallerArgumentExpression("expr")] string constraintExpression = "") { IConstraint constraint = expr.Resolve(); IncrementAssertCount(); ConstraintResult constraintResult = constraint.ApplyTo(del); if (!constraintResult.IsSuccess) ReportFailure(constraintResult, getExceptionMessage(), actualExpression, constraintExpression); } public static void That(TestDelegate code, IResolveConstraint constraint, NUnitString message = default(NUnitString), [CallerArgumentExpression("code")] string actualExpression = "", [CallerArgumentExpression("constraint")] string constraintExpression = "") { That((object)code, constraint, message, actualExpression, constraintExpression); } public static void That(TestDelegate code, IResolveConstraint constraint, FormattableString message, [CallerArgumentExpression("code")] string actualExpression = "", [CallerArgumentExpression("constraint")] string constraintExpression = "") { That((object)code, constraint, message, actualExpression, constraintExpression); } public static void That(TestDelegate code, IResolveConstraint constraint, Func<string> getExceptionMessage, [CallerArgumentExpression("code")] string actualExpression = "", [CallerArgumentExpression("constraint")] string constraintExpression = "") { That((object)code, constraint, getExceptionMessage, actualExpression, constraintExpression); } public static void That<[System.Runtime.CompilerServices.Nullable(2)] TActual>(TActual actual, IResolveConstraint expression, NUnitString message = default(NUnitString), [CallerArgumentExpression("actual")] string actualExpression = "", [CallerArgumentExpression("expression")] string constraintExpression = "") { IConstraint constraint = expression.Resolve(); IncrementAssertCount(); ConstraintResult constraintResult = constraint.ApplyTo(actual); if (!constraintResult.IsSuccess) ReportFailure(constraintResult, message.ToString(), actualExpression, constraintExpression); } public static void That<[System.Runtime.CompilerServices.Nullable(2)] TActual>(TActual actual, IResolveConstraint expression, FormattableString message, [CallerArgumentExpression("actual")] string actualExpression = "", [CallerArgumentExpression("expression")] string constraintExpression = "") { IConstraint constraint = expression.Resolve(); IncrementAssertCount(); ConstraintResult constraintResult = constraint.ApplyTo(actual); if (!constraintResult.IsSuccess) ReportFailure(constraintResult, message.ToString(), actualExpression, constraintExpression); } public static void That<[System.Runtime.CompilerServices.Nullable(2)] TActual>(TActual actual, IResolveConstraint expression, Func<string> getExceptionMessage, [CallerArgumentExpression("actual")] string actualExpression = "", [CallerArgumentExpression("expression")] string constraintExpression = "") { IConstraint constraint = expression.Resolve(); IncrementAssertCount(); ConstraintResult constraintResult = constraint.ApplyTo(actual); if (!constraintResult.IsSuccess) ReportFailure(constraintResult, getExceptionMessage(), actualExpression, constraintExpression); } public static void ByVal([System.Runtime.CompilerServices.Nullable(2)] object actual, IResolveConstraint expression, string message = "", [CallerArgumentExpression("actual")] string actualExpression = "", [CallerArgumentExpression("expression")] string constraintExpression = "") { That(actual, expression, message, actualExpression, constraintExpression); } private static void ReportFailure(ConstraintResult result, string message, string actualExpression, string constraintExpression) { MessageWriter messageWriter = new TextMessageWriter(ExtendedMessage("Assert.That", message, actualExpression, constraintExpression), Array.Empty<object>()); result.WriteMessageTo(messageWriter); ReportFailure(messageWriter.ToString()); } [AsyncStateMachine(typeof(<ThatAsync>d__71))] public static Task ThatAsync(AsyncTestDelegate code, IResolveConstraint constraint, NUnitString message = default(NUnitString), [CallerArgumentExpression("code")] string actualExpression = "", [CallerArgumentExpression("constraint")] string constraintExpression = "") { <ThatAsync>d__71 stateMachine = default(<ThatAsync>d__71); stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create(); stateMachine.code = code; stateMachine.constraint = constraint; stateMachine.message = message; stateMachine.actualExpression = actualExpression; stateMachine.constraintExpression = constraintExpression; stateMachine.<>1__state = -1; stateMachine.<>t__builder.Start(ref stateMachine); return stateMachine.<>t__builder.Task; } [AsyncStateMachine(typeof(<ThatAsync>d__72))] public static Task ThatAsync(AsyncTestDelegate code, IResolveConstraint constraint, FormattableString message, [CallerArgumentExpression("code")] string actualExpression = "", [CallerArgumentExpression("constraint")] string constraintExpression = "") { <ThatAsync>d__72 stateMachine = default(<ThatAsync>d__72); stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create(); stateMachine.code = code; stateMachine.constraint = constraint; stateMachine.message = message; stateMachine.actualExpression = actualExpression; stateMachine.constraintExpression = constraintExpression; stateMachine.<>1__state = -1; stateMachine.<>t__builder.Start(ref stateMachine); return stateMachine.<>t__builder.Task; } [AsyncStateMachine(typeof(<ThatAsync>d__73<>))] public static Task ThatAsync<[System.Runtime.CompilerServices.Nullable(2)] T>(Func<Task<T>> code, IResolveConstraint constraint, NUnitString message = default(NUnitString), [CallerArgumentExpression("code")] string actualExpression = "", [CallerArgumentExpression("constraint")] string constraintExpression = "") { <ThatAsync>d__73<T> stateMachine = default(<ThatAsync>d__73<T>); stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create(); stateMachine.code = code; stateMachine.constraint = constraint; stateMachine.message = message; stateMachine.actualExpression = actualExpression; stateMachine.constraintExpression = constraintExpression; stateMachine.<>1__state = -1; stateMachine.<>t__builder.Start(ref stateMachine); return stateMachine.<>t__builder.Task; } [AsyncStateMachine(typeof(<ThatAsync>d__74<>))] public static Task ThatAsync<[System.Runtime.CompilerServices.Nullable(2)] T>(Func<Task<T>> code, IResolveConstraint constraint, FormattableString message, [CallerArgumentExpression("code")] string actualExpression = "", [CallerArgumentExpression("constraint")] string constraintExpression = "") { <ThatAsync>d__74<T> stateMachine = default(<ThatAsync>d__74<T>); stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create(); stateMachine.code = code; stateMachine.constraint = constraint; stateMachine.message = message; stateMachine.actualExpression = actualExpression; stateMachine.constraintExpression = constraintExpression; stateMachine.<>1__state = -1; stateMachine.<>t__builder.Start(ref stateMachine); return stateMachine.<>t__builder.Task; } } }