using System; using System.Collections.Generic; using System.Reflection; using UnitTestSharp.Extensions; namespace UnitTestSharp { public class TestFinder { public static Type[] FindFixturesToTest(Type[] typesArray) { if (typesArray == null || typesArray.Length <= 0) return new Type[0]; List typesList = new List(); //Find all types in this assembly that are fixtures foreach (Type type in typesArray) { if (type.HasAttribute(typeof(IgnoreFixtureAttribute))) continue; if (type.BaseType == typeof(TestFixture)) typesList.Add(type); } return typesList.ToArray(); } /// /// Finds methods in the given type that we can try to test. /// /// The type to search through /// A list that will be populated /// with any methods we can't access (non public), but that aren't marked with an ignore flag. /// A readonly collection of methods that should be tested. public static IList FindTestableMethodsInFixture(Type type, ref List missingIgnoreAttr, out int ignored) { List methods = null; var returnMe = new List(); ignored = 0; // Search for private methods methods = new List( type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic)); // Check to see if any of them don't have the IgnoreMethod attribute foreach(MethodInfo method in methods) { if (method.IsVirtual) { //auto ignored always } else if (!method.HasAttribute(typeof(IgnoreTestAttribute))) { // this method will have to be ignored, even though it's not marked as such, // because it isn't public, so alert the user by adding it to this list missingIgnoreAttr.Add(method); } else { //ignoring this method ++ignored; } } // Now search for the public methods var methodsArray = type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); methods = new List(methodsArray); // Any that aren't marked as ignore will be added to the list of methods to test foreach (MethodInfo method in methods) { if (method.HasAttribute(typeof(IgnoreTestAttribute))) ++ignored; else if (!method.IsVirtual) returnMe.Add(method); } return returnMe.AsReadOnly(); } public static bool IsTestFixture(Type type) { return type == typeof(TestFixture); } /// /// Searches through an array of types to construct a list /// containing all the types which directly inherit from test fixture. /// /// An array of types to search through /// public static IList FindTestableFixtures(Type[] types) { var returnMe = new List(); foreach (Type type in types) if (IsTestFixture(type)) returnMe.Add(type); return returnMe.AsReadOnly(); } public static Type[] FindAllTypesInEntryAssembly() { return System.Reflection.Assembly.GetEntryAssembly().GetTypes(); } } }