c# - 在 Microsoft 测试资源管理器中创建具有相同工作项 ID 的测试方法的播放列表

标签 c# .net testing test-explorer

我在 Microsoft 测试管理器中有一个测试套件。每个测试都映射到特定的 WorkItem ID。我想将具有相同工作项 ID 的所有测试作为播放列表一起运行。下面是 sample 测试的例子。

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

我试过但无法通过 Workitem id 制作播放列表。请建议是否可以这样做。

最佳答案

你将不得不使用反射。
获取您的类的类型,获取其方法,然后搜索具有正确属性的方法。

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

请注意,您可以根据需要检查多个属性。
然后,您只需使用父类的实例作为启动这些方法的目标。

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

如果您的方法有参数,请将 null 替换为包含参数的 object[]

这里有一个完整的工作示例供您尝试:

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

关于c# - 在 Microsoft 测试资源管理器中创建具有相同工作项 ID 的测试方法的播放列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39524947/

相关文章:

.net - 如何找到特定 dll 的 PublicKeyToken?

windows - 主要测试环境-是通用操作系统还是将来的操作系统?

testing - forecast::checkresiduals 和 Box.test 的不同结果

c# - 在 C# 中构建文件路径的最佳实践

c# - 如何从 Span<T> 创建 Memory<T>?

c# - 为什么 HttpSessionState 不实现 IDictionary?

java - JUnit如何测试多个函数

c# - 如何使用 IHttpClientFactory 刷新 token

c# - 变量本身是否消耗内存?

c# - 从后面的代码访问 javascript 函数