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

PropertyConstraint

PropertyConstraint extracts a named property and uses its value as the actual value for a chained constraint.
using NUnit.Compatibility; using System; using System.Reflection; namespace NUnit.Framework.Constraints { public class PropertyConstraint : PrefixConstraint { private readonly string name; private object propValue; public PropertyConstraint(string name, IConstraint baseConstraint) : base(baseConstraint) { this.name = name; base.DescriptionPrefix = "property " + name; } public override ConstraintResult ApplyTo<TActual>(TActual actual) { Guard.ArgumentNotNull(actual, "actual"); Type type = actual as Type; if ((object)type == null) type = actual.GetType(); PropertyInfo property = TypeExtensions.GetProperty(type, name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((object)property == null) throw new ArgumentException($"""{name}""", "name"); propValue = property.GetValue(actual, null); ConstraintResult constraintResult = base.BaseConstraint.ApplyTo(propValue); return new ConstraintResult(this, constraintResult.ActualValue, constraintResult.IsSuccess); } protected override string GetStringRepresentation() { return $"""{name}""{base.BaseConstraint}"""; } } }