您的位置:首页 > 其它

仿Nunit的【TEST】属性测试一段程序

2008-10-12 20:57 375 查看
做一个WEB服务项目时,经常要调试一段函数是否执行正确。经自己研究Nunit,自己编写了一个小型的测试工具:

一:添加一个custom attribute named "TestAttribute" the code is:

[AttributeUsage(AttributeTargets.All,AllowMultiple=false)]

public class TestAttribute :System.Attribute

{

public TestAttribute()

{

}

}

二:创建一个Console程序:

class Program

{

static void Main()

{

RunTestMethod(null);

}

static void RunTestMethod(Assembly assembly)

{

assembly = Assembly.GetExecutingAssembly();

Type[] types=assembly.GetTypes();

for (int i = 0; i < types.Length; i++)

{

Type type = types[i];

foreach (MethodInfo method in type.GetMethods())

{

object[] atrList = method.GetCustomAttributes(typeof(TestAttribute), false);

if (atrList.Length >= 1)

{

object instance = Activator.CreateInstance(type);

object[] parameters = new object[2];

parameters[0] = "panbo";

parameters[1] = "ningjiao";

try

{

method.Invoke(instance, parameters);

}

catch(Exception e)

{

Console.WriteLine(e.Message);

}

}

}

}

Console.ReadKey();

}


三:然后在你想测试的方法前面加一个属性[Test()]

这样就可以测试了!

例如:

[Test()]

public void xx(string aa,string bb)

{

Console.WriteLine("xx method");

Console.WriteLine(aa);

Console.WriteLine(bb);

}

第一次写文章,写得很差。呵呵!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: