大家知道,在javaee各技術裡面,註解被廣泛的使用。那麼註解是如何?的呢。
額。。下面就給出一個本菜鳥 寫的一個 仿製 junit測試單元的一個 灰常簡單的myTest註解(本人學僧,第一次寫部落格,希望大家多提寶貴意見。。)
/** * */package com.guxiang.test;
/** * */package com.guxiang.test;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;首先自訂一個 myTest註解/** * @author guxiang * @date 2016年12月24日 下午10:22:11 * 自訂的myTest註解 */@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE})public @interface MyTest { long time() default -1;}
寫一個類 用於被myTest註解 實現測試
package com.guxiang.test;public class SomeDaoImpl { public void save(){ System.out.println("儲存了資料"); } public void update(){ System.out.println("更新了資料"); }}
寫一個測試類別 這個類 引用myTest註解
package com.guxiang.test;public class SomeDaoImplTest { private SomeDaoImpl dao= new SomeDaoImpl(); /** * 測試添加 */ @MyTest public void testAdd(){ dao.save(); } @MyTest public void testUpdate(){ dao.update(); }}
最關鍵的 一步 寫一個 myTestRunner類 使用反射實現註解的功能 給註解注入靈魂
/** * */package com.guxiang.test;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/** * @author guxiang * @date 2016年12月24日 下午10:26:07 */// 反射註解public class MyTestRunner { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { Class clazz = SomeDaoImplTest.class; Method[] ms = clazz.getMethods(); for (Method method : ms) { boolean hasMyTest = method.isAnnotationPresent(MyTest.class); if (hasMyTest) { method.invoke(clazz.newInstance(), null); } } }}
這個測試類別仿製了 junit測試單元
執行MyTestRunner 的main方法 後 會在控制台輸出以下
儲存了資料
更新了資料
於此就得到了 測試那個被測試類別的功能。。