使用Reflection在测试方法内部读取类别属性 [英] Reading Category attribute inside test method using Reflection
问题描述
我试图使用 TestMethod
自定义属性的category属性通过使用反射读取.dll来添加测试方法,如下所示:
I'm trying to add test methods using the category property of the TestMethod
custom attribute by reading a .dll using reflection, something like this:
如果测试方法是:
[TestMethod, Category("xyz"), Category("abc")]
public void VerifySomething()
{
//some code
}
我正在使用这样的反射读取.dll:
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
continue;
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);
}
}
}
}
使用这个我无法添加由特定类别过滤的树视图节点中的测试方法。
基本上我想要的是从dll读取TestCategoryAttribute,它的值类似于xyz或abc根据我上面提到的例子,然后基于过滤器(TestCategoryAttribute)值我想加载方法从dll并将它们添加到treeview节点。
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.
推荐答案
这是如何获得一个 TestMethod
作为 MethodInfo
从 Reflection 。
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
给定一个 TestMethod
_t
(假设一切正常到那里),你可以得到以下类别
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));
如何根据某些条件过滤它们?
执行Linq 任何
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...
这篇关于使用Reflection在测试方法内部读取类别属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!