2

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()
msbyuva
  • 3,467
  • 13
  • 63
  • 87

1 Answers1

3

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

Community
  • 1
  • 1
venerik
  • 5,766
  • 2
  • 33
  • 43
  • thanks for showing me the way how to do it & providing the source. – msbyuva Oct 09 '15 at 20:09
  • In my case for the test I have three categories, when I execute the test -- I am logging the test category. From VSConsole when I am executing based on TestCaseFilter, but it's logging three categories. Can I explicitly set something which tells tetscase is set to run under this category -- TestCaseFilter – msbyuva Oct 09 '15 at 20:43
  • I don't know. I suggest you post a new question for that. – venerik Oct 10 '15 at 07:30