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