In MSTest how to find the total number of tests to run in ClassInitialize or AssemblyInitialize?

喜夏-厌秋 提交于 2019-12-24 05:29:32

问题


Using MStest - I want to find the total number of test methods which are queued for run.

How should I capture this value in ClassInitialize() or AssemblyInitialize() method.

Only thing I get is TestContext which has no details of total number of tests.


回答1:


I actually have an answer to this one, but you have to use Reflection to do it. This method gets all of the tests in the class and runs them. Each test starts with the string "TC" for test case. -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;
        }

    }


来源:https://stackoverflow.com/questions/17715850/in-mstest-how-to-find-the-total-number-of-tests-to-run-in-classinitialize-or-ass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!