在MSTest中如何找到在ClassInitialize或AssemblyInitialize中运行的测试总数?

时间:2013-07-18 06:14:26

标签: c# unit-testing mstest coded-ui-tests

使用MStest - 我想找到排队等待运行的测试方法的总数。

我应该如何在ClassInitialize()AssemblyInitialize()方法中捕获此值。

我得到的只是TestContext,它没有测试总数的细节。

1 个答案:

答案 0 :(得分:1)

我实际上对此有一个答案,但是您必须使用反射来做到这一点。此方法获取该类中的所有测试并运行它们。每个测试以测试用例的字符串“ TC”开头。 -sulu

public async Task RunServiceTests()
    {

        // Find the list of Test Cases in the running assembly

        // all methods that start with "TC"
        Assembly assembly = Assembly.GetExecutingAssembly();
        Type[] types = assembly.GetExportedTypes();
        string testCaseString = "TC";
        Dictionary<long, MethodInfo> dictionary = new Dictionary<long, MethodInfo>();
        long testCaseNumber = 0;
        MethodInfo[] methods = null;
        foreach (Type t in types)
        { if(t.Name == "ServicesTests")
            {
                methods = t.GetMethods();

                foreach (MethodInfo method in methods)
                {
                    Regex regex = new Regex(@"TC\d+");
                    Match match = regex.Match(m.Name);
                    if (match.Success)
                    {
                        simpleLogger.WriteLine("Method Name:  " + method.Name);

                        int pos = -1;
                        string name = method.Name;
                        pos = name.IndexOf("_");
                        int length = pos - 2;
                        testCaseString = name.Substring(2, length);
                        simpleLogger.LogInfo("Test Case Number found: " + testCaseString);
                        testCaseNumber = Convert.ToInt64(testCaseString);

                        if (!dictionary.ContainsKey(testCaseNumber))
                        {
                            dictionary.Add(testCaseNumber, method);
                        }


                    }

                } // End of methodInfo loop

                break;
            }

        }

        foreach (KeyValuePair<long, MethodInfo> kvp in dictionary)
        {
            MethodInfo method = kvp.Value;
            Task task = (Task) method.Invoke(Instance, null);
             await task;
        }

    }