如何使用C#,Visual Studio MS Test为测试用例获取TestCategory

如何使用C#,Visual Studio MS Test为测试用例获取TestCategory,c#,mstest,categories,testcaseattribute,C#,Mstest,Categories,Testcaseattribute,我希望在运行时使用c#查找测试用例的测试类别。我正在使用MSTEST,TestContext没有任何与TestCategory相关的信息,我想捕获/记录TestCategory信息。在我的例子中,我为一个测试用例分配了多个测试类别。。范例 BaseTest将具有初始化和清理方法 [TestClass] public class CustomerTest : BaseTest { [TestMethod] [TestCategory("Smoke")

我希望在运行时使用c#查找测试用例的测试类别。我正在使用MSTEST,TestContext没有任何与TestCategory相关的信息,我想捕获/记录TestCategory信息。在我的例子中,我为一个测试用例分配了多个测试类别。。范例

BaseTest将具有初始化和清理方法

[TestClass]
    public class CustomerTest : BaseTest
    {
        [TestMethod]
        [TestCategory("Smoke")]
        [TestCategory("regression")]
        public void Login()

您可以使用反射来获取测试方法内部的属性,如下所示:

[TestMethod]
[TestCategory("Smoke")]
[TestCategory("regression")]
public void Login()
{
    var method = MethodBase.GetCurrentMethod();
    foreach(var attribute in (IEnumerable<TestCategoryAttribute>)method
        .GetCustomAttributes(typeof(TestCategoryAttribute), true))
    {
        foreach(var category in attribute.TestCategories)
        {
            Console.WriteLine(category);
        }
    }
    var categories = attribute.TestCategories;  
}
如上文所述,获取方法库和属性


Source:

感谢您向我展示了如何做并提供了源代码。在我的测试中,我有三个类别,当我执行测试时——我正在记录测试类别。当我基于TestCaseFilter执行时,从VSConsole,但它记录了三个类别。我可以显式地设置一些东西来告诉tetscase被设置为在这个类别下运行——TestCaseFilterI不知道。我建议你为此贴一个新问题。
var method = typeof(TheTestClass).GetMethod("Login");