AttributeExists Constraint
AttributeExistsConstraint tests for the existence of an attribute on a type.
Usage
Has.Attribute(Type attributeType)
Has.Attribute<TAttribute>()
The generic form requires TAttribute : Attribute, so passing a type that isn't an attribute is a compiler error.
Note
In NUnit 4 and earlier, the generic form accepted any type. Passing a type that isn't an attribute compiled, but the test failed when it ran.
Examples
[Serializable]
public class SerializableClass { }
[Test]
public void AttributeExistsConstraint_Examples()
{
// Test that a type has an attribute
Assert.That(typeof(SerializableClass), Has.Attribute<SerializableAttribute>());
// Negative test
Assert.That(typeof(TypeConstraintSnippets), Has.No.Attribute<SerializableAttribute>());
}
Notes
- When no further constraint is chained,
Has.Attributecreates anAttributeExistsConstraint. - When a constraint is chained (e.g.,
.Property("Name")), it becomes an AttributeConstraint. - The constraint works on any object that implements
ICustomAttributeProvider, such asType,MethodInfo, andAssembly.
See Also
- Attribute Constraint - Test attribute properties