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;
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 (type == (Type)null)
type = actual.GetType();
PropertyInfo ultimateShadowingProperty = Reflect.GetUltimateShadowingProperty(type, name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (ultimateShadowingProperty == (PropertyInfo)null)
throw new ArgumentException($"""{name}""{type}""", "name");
propValue = ultimateShadowingProperty.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}""";
}
}
}