C# --- 使用Attribute + Reflection的例子
背景
E2E是对workflow的测试,将所有E2E test case定义在一个可执行程序里(exe), 定时自动运行
如何定义和执行TestCase
将需要执行的TestCase包装成一个类,并将TestCase分成几个Steps,每个Step是一个方法 自定义一个Attribute,修饰每个Step方法
public class StepMethodAttribute : Attribute
{
public string Pattern { get ; set ; }
public StepMethodAttribute ( string pattern)
{
Pattern = pattern;
}
}
public class UserSignUpAndLoginSteps : CommonSteps
{
[ StepMethod ( "Create a user" ) ]
public static async Task< bool > CreateAUserAsync ( TestStep testStep)
{
}
[ StepMethod ( "Login user" ) ]
public static Task< bool > LoginUser ( TestStep testStep)
{
}
}
使用反射拿到所有被自定义Attribute “StepMethod” 修饰的方法.
var assembly = Assembly. GetExecutingAssembly ( ) ;
var types = assembly. GetTypes ( ) ;
var classes = types. Where ( x => x. IsClass) . ToList ( ) ;
var allMethods = classes. SelectMany ( x => x. GetMethods ( ) ) . ToList ( ) ;
var testCaseStepMethods = allMethods. Where ( x => x. GetCustomAttribute ( typeof ( StepMethodAttribute ) , false ) != null ) . ToList ( ) ;
var step = CreateTestStep ( ) ;
tasks = testCaseStepMethods. select ( methodInfo => methodInfo. invoke ( null , step) )