Test-Driven Test Development

Making it Go Green

Discovering Tests in DLLs

Our minispec.exe program is currently seeing a list of paths to DLL files.

Let’s load the provided DLLs and find our defined test methods inside of them!

Get List of Methods in DLL

First, let’s update the test to print out a list of methods from the provided DLL.

Update MiniSpec/Program.cs to the following:

using System;
using System.Reflection;
using System.Runtime.Loader;

foreach (var dll in args) {
    Console.WriteLine($"Loading {dll}");
    var dllPath = System.IO.Path.GetFullPath(dll);
    var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(dllPath);

    foreach (var type in assembly.GetTypes()) {
        Console.WriteLine($"Found type: {type}");
        foreach (var method in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance))
            Console.WriteLine($"Instance Method: {method.Name}");
        foreach (var method in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static))
            Console.WriteLine($"Static Method: {method.Name}");
    }
}
Review
  • Load any argument as a .NET DLL assembly
  • Loop over every defined type in the assembly (args is available to top-level statements)
  • Loop over every instance method on the type (and print out the method name)
  • Loop over every static method on the type (and print out the method name)

Run the tests again with dotnet test (excerpt below)

Not found: PASS TestShouldPass
In value:  Loading MyTests.dll
Found type: <Program>$
Instance Method: MemberwiseClone
Instance Method: Finalize
Static Method: <Main>$
Static Method: <<Main>$>g__TestShouldPass|0_0
Static Method: <<Main>$>g__TestShouldFail|0_1

The test is still failing (“Not found: PASS TestShouldPass”) but we can see new output, which is good!

Even though we did not explicitly define it, C# 9 added a <Program> class for us.

As you would expect from a console application, this class has a static <Main> method.

And it looks like we found the test methods which we defined as top-level statements too!

Huh. <<Main>$>g__TestShouldPass|0_0. I guess that’s how local methods are represented.