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

AttributeConstraint

AttributeConstraint tests that a specified attribute is present on a Type or other provider and that the value of the attribute satisfies some other constraint.
using NUnit.Compatibility; using System; using System.Reflection; namespace NUnit.Framework.Constraints { public class AttributeConstraint : PrefixConstraint { private readonly Type expectedType; private Attribute attrFound; public AttributeConstraint(Type type, IConstraint baseConstraint) : base(baseConstraint) { expectedType = type; base.DescriptionPrefix = "attribute " + expectedType.FullName; if (!typeof(Attribute).GetTypeInfo().IsAssignableFrom(expectedType.GetTypeInfo())) throw new ArgumentException($"""{expectedType}""", "type"); } public override ConstraintResult ApplyTo<TActual>(TActual actual) { Guard.ArgumentNotNull(actual, "actual"); Attribute[] customAttributes = AttributeHelper.GetCustomAttributes(actual, expectedType, true); if (customAttributes.Length == 0) throw new ArgumentException($"""{expectedType}""", "actual"); attrFound = customAttributes[0]; return base.BaseConstraint.ApplyTo(attrFound); } protected override string GetStringRepresentation() { return $"""{expectedType}""{base.BaseConstraint}"""; } } }