I needed a component that would examine a directory and find all test assemblies in a directory. This sounded like a job for LINQ.
var allFiles = from fileName in Directory.GetFiles(directory.FullName, "*.dll")
let assembly = Assembly.LoadFile(fileName)
let types = assembly.GetExportedTypes()
from Type t in types
where t.GetCustomAttributes(typeof(TestClassAttribute), true).Length > 0
select assembly ;
The above LINQ query will:
- Get all DLL (assemblies) files.
- Use the *non-preferred* way to load each of the files as an assembly using Assembly.LoadFile()
- Reflect all the public types in the assembly using Assembly.GetExportedTypes()
- Retrieve an array of any TestClassAttributes from each type and check to see if there are any
- Put the results of into an IEnumerable<Assembly>
Using this above, in a single statement, I have a managable list of all assemblies in the directory that have a least on MSTest test class in them.