Search code examples
c#unit-testingmstestcoded-ui-tests

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


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.


Solution

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