簡體   English   中英

使用反射讀取測試方法內的類別屬性

[英]Reading Category attribute inside test method using Reflection

我試圖通過使用反射讀取.dll來使用TestMethod自定義屬性的category屬性添加測試方法,如下所示:

如果測試方法是:

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

我正在使用反射來讀取.dll,如下所示:

 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節點。 有人可以指導我如何實現這一目標。

這是從Reflection中獲取TestMethod作為MethodInfo

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

給定一個TestMethod _t (假設一切都正確到那里),您可以使用以下內容獲取類別

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

如何根據某些條件過濾它們? Linq Any可以解決問題嗎?

    if testCategories.Any(c => c == "xyz" || c == "abc") )
    {
        // then add to the treeview node, etc...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM