Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a playlist of test methods having same workitem id in Microsoft test explorer

I have a test suite in Microsoft test manager. Each test is mapped to certain WorkItem ID. I want to run all tests having same workitem id together as a playlist. Below is exmaple of sample test.

    [TestMethod]
        [TestCategory("Cat A")]
        [Priority(1)]
        [WorkItem(5555)]
        public void SampleTest()
        {
           Do some thing
        }

I tried but was not able to make a playlist by Workitem id. Please suggest if it is possible to do so.

like image 449
Madhur Maurya Avatar asked Oct 29 '22 20:10

Madhur Maurya


1 Answers

You will have to use reflection.
Get your class's type, get its methods then search for those that have the correct attribute(s).

MethodInfo[] methods = yourClassInstance.GetType()
    .GetMethods()).Where(m => 
    {
        var attr = m.GetCustomAttributes(typeof(WorkItem), false);
        return attr.Length > 0 && ((WorkItem)attr[0]).Value == 5555;
    })
    .ToArray();

Note that you can check multiple attributes if you'd like.
You then only have to use an instance of the parent class as a target for launching these methods.

foreach (var method in methods)
{
    method.Invoke(yourClassInstance, null);
}

If your methods have parameters, replace null with an object[] containing the parameters.

Here's a full working example for you to try:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication7
{
    public class MyAttribute : Attribute
    {
        public MyAttribute(int val)
        {
            Value = val;
        }

        public int Value { get; set; }
    }

    class Test
    {
        [MyAttribute(1)]
        public void Method1()
        {
            Console.WriteLine("1!");
        }
        [MyAttribute(2)]
        public void Method2()
        {
            Console.WriteLine("2!");
        }
        [MyAttribute(3)]
        public void Method3()
        {
            Console.WriteLine("3!");
        }
        [MyAttribute(1)]
        public void Method4()
        {
            Console.WriteLine("4!");
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            var test = new Test();

            var types = Assembly.GetAssembly(test.GetType()).GetTypes();

            MethodInfo[] methods = test.GetType().GetMethods()
                .Where(m => 
                    {
                        var attr = m.GetCustomAttributes(typeof(MyAttribute), false);
                        return attr.Length > 0 && ((MyAttribute)attr[0]).Value == 1;
                    })
                .ToArray();

            foreach (var method in methods)
            {
                method.Invoke(test, null);
            }
        }
    }
}
like image 132
Kilazur Avatar answered Nov 15 '22 05:11

Kilazur