ProcessorTest.java
package br.com.waslleysouza.zz;
import java.lang.reflect.Method;
public class ProcessorTest {
public ProcessorTest() {
super();
}
public static void process(String clazz) throws ClassNotFoundException
{
int passed = 0;
int failed = 0;
for(Method m : Class.forName(clazz).getMethods())
{
if(m.isAnnotationPresent(Testable.class))
{
try
{
m.invoke(null);
passed++;
}
catch(Exception ex)
{
System.out.println("方法"+m+"运行失败,异常:"+ex.getCause());
failed++;
}
}
}
System.out.println("共运行了:"+(passed+failed)+"个方法,其中:\n"+"失败了:"+failed+"个,\n"+"成功了:"+passed+"个!");
}
}
-----------------------------------
MyTest.java
package br.com.waslleysouza.zz;
public class MyTest {
public MyTest() {
super();
}
@Testable
public static void m1()
{}
public static void m2()
{}
@Testable
public static void m3()
{
throw new IllegalArgumentException("参数出错了!");
}
public static void m4()
{
}
@Testable
public static void m5()
{
}
public static void m6()
{
}
@Testable
public static void m7()
{
throw new IllegalArgumentException("程序业务出现异常");
}
public static void m8()
{
}
}
-------------------------Testable.java------------------------
package br.com.waslleysouza.zz;
import java.lang.annotation.*;
/**
* Description:
* <br/>Copyright (C), 2005-2008, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Testable
{
}
-------------RunTests.java-------------------------------
package br.com.waslleysouza.zz;
public class RunTests {
public RunTests() {
super();
}
public static void main(String[] args) throws Exception {
ProcessorTest.process("MyTest");
}
}
本文介绍了一个简单的Java单元测试框架实现,通过注解@Testable标记的方法将被自动执行并报告测试结果,展示了基本的测试流程及异常处理。
399

被折叠的 条评论
为什么被折叠?



