2

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.

SarkarG
  • 687
  • 1
  • 8
  • 30
  • I think this is not possible. Why do you want this? – chaliasos Jul 18 '13 at 06:27
  • I want to call the cleanup of base class only when all the test are finished, but I am unable to do so because ClassCleanup and AssemblyCleanup are static. I can't modify the test framework (base class) also. So thought if i would start a counter and call base.cleanup() from TestCleanup() when counter reaches to last test. – SarkarG Jul 18 '13 at 07:16
  • 1
    Use the `AssemblyCleanup` then. By default it will be called when the test run has finished. – chaliasos Jul 18 '13 at 07:20
  • 1
    You might store a reference to the base object in a `static` that `ClassCleanup` or `AssemblyCleanup` could use to call the base clean up code. **BUT** before doing that I suggest you check when the constructors of the two classes (ie base class and test class) are called. I created a simple test project containing all the `...Initialize()`, `...Cleanup()` and class constructors possible for two tests in each of two test class files. Each of these methods (about 18) contained a `WriteLine()` that printed the method name and purpose. This little project told me what was called and when. – AdrianHHH Jul 18 '13 at 13:15
  • There is a simular testset provided as an example in the documentation: http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assemblycleanupattribute.aspx – oɔɯǝɹ Apr 11 '14 at 18:37

2 Answers2

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

    }
Su Llewellyn
  • 2,660
  • 2
  • 19
  • 33
0

I have been using the following method to do this after countless tries.

/// <summary>
/// Gets the number of test methods in the specified class.
/// </summary>
/// <param name="testClass">The Type object representing the class to be checked.</param>
/// <returns>The number of test methods in the class.</returns>
public int GetNumberOfTestMethods(Type testClass)
{
    var withTestAttribute = testClass.GetMethods()
        .Where(m => m.GetCustomAttributes(typeof(TestMethodAttribute), false).Any());

    return withTestAttribute.Count();
}

You may call this method like this in a SampleTest class.

var count = GetNumberOfTestMethods(typeof(SampleTest))

For this to work, your test methods should have [TestMethod] attribute.

Alternatively (if you want more control over the filter) you can do this. But above solution is more optimized because it has no filters.

public int GetNumberOfTestMethods(Type testClass)
{
    var attributeData = testClass.GetMethods()
        .SelectMany(x => x.CustomAttributes)
        .Where(y => y.AttributeType == typeof(TestMethodAttribute)).ToList();
    return attributeData.Count;
}
Nishan
  • 3,644
  • 1
  • 32
  • 41