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

ExactCountConstraint

ExactCountConstraint applies another constraint to each item in a collection, succeeding only if a specified number of items succeed.
using NUnit.Framework.Internal; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.CompilerServices; namespace NUnit.Framework.Constraints { [NullableContext(1)] [Nullable(0)] public class ExactCountConstraint : Constraint, IEnumerableConstraint, IConstraint, IResolveConstraint { private readonly int _expectedCount; [Nullable(2)] private readonly IConstraint _itemConstraint; public override string Description { get { object obj; if (_expectedCount != 0) { if (_expectedCount != 1) { DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(14, 1); defaultInterpolatedStringHandler.AppendLiteral("exactly "); defaultInterpolatedStringHandler.AppendFormatted(_expectedCount); defaultInterpolatedStringHandler.AppendLiteral(" items"); obj = defaultInterpolatedStringHandler.ToStringAndClear(); } else obj = "exactly one item"; } else obj = "no item"; string text = (string)obj; if (_itemConstraint == null) return text; return PrefixConstraint.FormatDescription(text, _itemConstraint); } } public ExactCountConstraint(int expectedCount) : base(Array.Empty<object>()) { _expectedCount = expectedCount; } public ExactCountConstraint(int expectedCount, IConstraint itemConstraint) : base(itemConstraint) { Guard.ArgumentNotNull(itemConstraint, "itemConstraint"); _itemConstraint = itemConstraint.Resolve(); _expectedCount = expectedCount; } public override ConstraintResult ApplyTo<[Nullable(2)] TActual>(TActual actual) { IEnumerable source = ConstraintUtils.RequireActual<IEnumerable>(actual, "actual"); Type type = TypeHelper.FindPrimaryEnumerableInterfaceGenericTypeArgument(typeof(TActual)); if ((object)type != null && !(type == typeof(object))) return Reflect.InvokeApplyToEnumerable(this, actual, type); return ApplyToEnumerable(actual, source.Cast<object>()); } public ConstraintResult ApplyToEnumerable<[Nullable(2)] TActual, [Nullable(2)] TItem>(TActual actual, IEnumerable<TItem> enumerable) { Collection<object> collection = new Collection<object>(); int num = 0; foreach (TItem item in enumerable) { if (_itemConstraint != null) { if (_itemConstraint.ApplyTo(item).IsSuccess) num++; } else num++; if (collection.Count <= 10) collection.Add((object)item); } return new ExactCountConstraintResult(this, actual, num == _expectedCount, num, collection); } } }