How to get TestCategory for a Testcase using C#, Visual Studio MS Test

7.3k Views Asked by At

I am looking to find Test Category of a testcase at runtime using c#. I am using MSTEST, TestContext does not have any information related to TestCategory, I want to capture/log TestCategory information. In my case I have multiple TestCATEGORIES assigned to a testcase.. Example

BaseTest will have Initialization and CleanUp methods..

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

There are 1 best solutions below

3
On BEST ANSWER

You can use reflection to get the attributes inside a test method like this:

[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;  
}

If you want to get the categories at another place than inside the test method you can use

var method = typeof(TheTestClass).GetMethod("Login");

to get the method base and get the attributes as described above.

Source: Read the value of an attribute of a method