做一个WEB服务项目时,经常要调试一段函数是否执行正确。经自己研究Nunit,自己编写了一个小型的测试工具:
一:添加一个custom attribute named "TestAttribute" the code is:
[AttributeUsage(AttributeTargets.All,AllowMultiple=false)]
public class TestAttribute :System.Attribute
{
public TestAttribute()
{
}
}
二:创建一个Console程序:

Code
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);
}
第一次写文章,写得很差。呵呵!
posted @ 2008-10-12 20:57 Eric pan 阅读(100) 评论(0)
编辑