csharp / expert
Snippet
Automated Suite Inspection via Reflection
Expert testing often involves building custom discovery mechanisms. Using Reflection to inspect metadata (Attributes) at runtime allows for the creation of dynamic test runners that don't require hardcoded method calls. This technique is fundamental for understanding how modern testing frameworks and dependency injection containers operate internally.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System.Reflection;[AttributeUsage(AttributeTargets.Method)]public class ExpertTestAttribute : Attribute { }public class TestRunner{public void RunTests(object testInstance){var methods = testInstance.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => m.GetCustomAttribute<ExpertTestAttribute>() != null);foreach (var method in methods){try{method.Invoke(testInstance, null);Console.WriteLine($"Passed: {method.Name}");}catch (TargetInvocationException ex){Console.WriteLine($"Failed: {method.Name} - {ex.InnerException?.Message}");}}}}
Breakdown
1
.Where(m => m.GetCustomAttribute<ExpertTestAttribute>() != null)
Filters class methods to find only those decorated with a specific metadata marker.
2
method.Invoke(testInstance, null)
Dynamically executes the method on the provided instance without compile-time knowledge of the method name.