2

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.

1
  • 1
    If the answer is right for you, please mark it as correct. This helps other people to find the solution faster.
    – jlvaquero
    Feb 10, 2015 at 13:46

1 Answer 1

1

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;
}
2
  • jlvaquero, thank you for answer!=) but can you please write in c#?
    – 132u
    Jan 9, 2015 at 11:27
  • OK. I post C# because I forgot to chek the language tag of your question.
    – jlvaquero
    Jan 9, 2015 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.