Reputation: 21
I can retrieve all of the test names out of an NUnit test class library assembly, but I need to retrieve their category names as well from the parameter passed to the Category
attribute.
For example:
[Category("text")]
public void test() {}
I need to get "text"
from the DLL.
Upvotes: 2
Views: 190
Reputation: 8785
Using reflection.
For example:
Given this attribute applied to fields:
<AttributeUsage(AttributeTargets.Field)> _
Public NotInheritable Class DataBaseValueAttribute
Inherits Attribute
Private _value As Object
Public Sub New(ByVal value As Object)
_value = value
End Sub
Public Function GetValue() As Object
Return _value
End Function
End Class
You can use reflection to get field info from a type and get the attributes:
Dim tipo As Type = GetType(YourType)
Dim fi As FieldInfo = tipo.GetField("fieldName")
Dim attribs As Atributos.DataBaseValueAttribute() = CType(fi.GetCustomAttributes(GetType(Atributos.DataBaseValueAttribute), False), Atributos.DataBaseValueAttribute())
If attribs.Count > 0 Then
Return attribs(0).GetValue()
Else
Return Nothing
End If
In c#:
[AttributeUsage(AttributeTargets.Field)]
public sealed class DataBaseValueAttribute : Attribute
{
private object _value;
public DataBaseValueAttribute(object value)
{
_value = value;
}
public object GetValue()
{
return _value;
}
}
Type tipo = typeof(YourType);
FieldInfo fi = tipo.GetField("fieldName");
Atributos.DataBaseValueAttribute[] attribs = (Atributos.DataBaseValueAttribute[])fi.GetCustomAttributes(typeof(Atributos.DataBaseValueAttribute), false);
if (attribs.Count > 0) {
return attribs(0).GetValue();
} else {
return null;
}
Upvotes: 1