vivek singh vivek singh - 1 year ago 142
C# Question

Reading Category attribute inside test method using Reflection

I'm trying to add test methods using the category property of the

custom attribute by reading a .dll using reflection, something like this:

if the test method is:

[TestMethod, Category("xyz"), Category("abc")]
public void VerifySomething()
//some code

I'm reading the .dll using reflection like this:

Assembly _assembly = Assembly.LoadFile(AssembleyPath);
Type[] types = _assembly.GetExportedTypes();
foreach (Type type in types)
Attribute _classAttribute = type.GetCustomAttribute(typeof(TestClassAttribute));
if (_classAttribute != null)
TreeNode _n = new TreeNode();
_n.Text = type.Name;
if (type.Name.ToLower().Contains("testbase"))
// For exculding test base class from tree node list
MemberInfo[] members =
type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod);
foreach (MemberInfo member in members)

Attribute _att = member.GetCustomAttribute(typeof(TestMethodAttribute));
if (_att != null)
TestMethod _t = new TestMethod(member.Name);



Using this i'm unable to add test methods filtered by particular category inside treeview node.
Basically all i want is to read TestCategoryAttribute from dll which has value something like "xyz" or "abc" as per the example i've mentioned above and then based on the filter (TestCategoryAttribute) value i would want to load methods from the dll and add them to the treeview node. Can anybody please guide me how can i achieve that.

Answer Source

This is how to get a TestMethod as a MethodInfo from Reflection.

var _t= typeof(testClass).GetMethod(methodName); // testClass should be the type in your foreach

Given a TestMethod _t (assuming everything is right till there), you can get the categories with the following

var testCategories = IEnumerable<TestCategoryAttribute>)_t.GetCustomAttributes(typeof(TestCategoryAttribute), true));

How to filter them based on some conditions? Does a Linq Any do the trick?

    if testCategories.Any(c => c == "xyz" || c == "abc") )
        // then add to the treeview node, etc...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download