其实知道了如果编写自己的属性,那么对Nunit的实现机制就可以很明白了,Nunit就是通过反射获取测试类中方法和类的属性,然后进行相应处理的
假设有对象obj
Type type=obj.getType() 先获取该对象的Type 类型
TestFixtureAttribute [] AttributeArray = (TestFixtureAttribute []) type.GetCustomAttributes(typeof(TestFixtureAttribute ), false);
通过反射获得针对该对象的属性定义, 比如Nunit中针对测试类的[TestFixture]属性
MethodInfo minfo=type.getMethod(“方法名“);
获得该对象指定方法名的方法信息
TestAttribute [] AttributeArray = (TestAttribute []) minfo.GetCustomAttributes(typeof(TestAttribute ), false);
获得针对该方法的属性定义,比如Nunit测试类中针对方法的[Test]属性
Nunit实在在操作中,肯定是通过type.getMethods()方法获得所有方法信息,然后挨个分析方法的属性来确定那些方法需要测试的,比如当它碰到Ignore属性的时候就会跳过测试
由此可以猜测Ignore属性类基本是象如下定义的:
[AttributeUsage(AttributeTargets.Method)]
public class IgnoreAttribute : Attribute
{
private string describe;//描述信息
public IgnoreAttrebute(string info)
{describe=info;}
public string Describe;
{get{..};set{..};}
}
通过设置 AttributeTargets为Method表明该属性只能为方法所用,通过一个构造方法,就强制了在使用Ignore属性的时候必须输入一些描述信息,比如[Ignore(“测试通过“)]
假设有对象obj
Type type=obj.getType() 先获取该对象的Type 类型
TestFixtureAttribute [] AttributeArray = (TestFixtureAttribute []) type.GetCustomAttributes(typeof(TestFixtureAttribute ), false);
通过反射获得针对该对象的属性定义, 比如Nunit中针对测试类的[TestFixture]属性
MethodInfo minfo=type.getMethod(“方法名“);
获得该对象指定方法名的方法信息
TestAttribute [] AttributeArray = (TestAttribute []) minfo.GetCustomAttributes(typeof(TestAttribute ), false);
获得针对该方法的属性定义,比如Nunit测试类中针对方法的[Test]属性
Nunit实在在操作中,肯定是通过type.getMethods()方法获得所有方法信息,然后挨个分析方法的属性来确定那些方法需要测试的,比如当它碰到Ignore属性的时候就会跳过测试
由此可以猜测Ignore属性类基本是象如下定义的:
[AttributeUsage(AttributeTargets.Method)]
public class IgnoreAttribute : Attribute
{
private string describe;//描述信息
public IgnoreAttrebute(string info)
{describe=info;}
public string Describe;
{get{..};set{..};}
}
通过设置 AttributeTargets为Method表明该属性只能为方法所用,通过一个构造方法,就强制了在使用Ignore属性的时候必须输入一些描述信息,比如[Ignore(“测试通过“)]