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

PropertyConstraint

PropertyConstraint extracts a named property and uses its value as the actual value for a chained constraint.
using NUnit.Framework.Internal; using System; using System.Reflection; using System.Runtime.CompilerServices; namespace NUnit.Framework.Constraints { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public class PropertyConstraint : PrefixConstraint { private readonly string _name; [System.Runtime.CompilerServices.Nullable(2)] private object _propValue; public PropertyConstraint(string name, IConstraint baseConstraint) : base(baseConstraint, "property " + name) { _name = name; } public override ConstraintResult ApplyTo<[System.Runtime.CompilerServices.Nullable(2)] TActual>(TActual actual) { Guard.ArgumentNotNull(actual, "actual"); PropertyInfo ultimateShadowingProperty = Reflect.GetUltimateShadowingProperty(typeof(TActual), _name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((object)ultimateShadowingProperty == null && typeof(TActual).IsInterface) { Type[] interfaces = typeof(TActual).GetInterfaces(); foreach (Type type in interfaces) { ultimateShadowingProperty = Reflect.GetUltimateShadowingProperty(type, _name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((object)ultimateShadowingProperty != null) break; } } if ((object)ultimateShadowingProperty == null) { Type type2 = actual as Type; if ((object)type2 != null) ultimateShadowingProperty = Reflect.GetUltimateShadowingProperty(type2, _name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((object)ultimateShadowingProperty == null) { type2 = actual.GetType(); ultimateShadowingProperty = Reflect.GetUltimateShadowingProperty(type2, _name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((object)ultimateShadowingProperty == null) throw new ArgumentException($"""{_name}""{type2}""", "_name"); } } _propValue = ultimateShadowingProperty.GetValue(actual, null); ConstraintResult baseResult = base.BaseConstraint.ApplyTo(_propValue); return new PropertyConstraintResult(this, baseResult); } protected override string GetStringRepresentation() { return $"""{_name}""{base.BaseConstraint}"""; } } }