进阶day12-自定义简单的Junit框架
This commit is contained in:
18
javaSE-day12/src/com/inmind/annotation03/JunitDemo10.java
Normal file
18
javaSE-day12/src/com/inmind/annotation03/JunitDemo10.java
Normal file
@@ -0,0 +1,18 @@
|
||||
package com.inmind.annotation03;
|
||||
|
||||
public class JunitDemo10 {
|
||||
|
||||
public void method1(){
|
||||
System.out.println("测试方法1执行了");
|
||||
}
|
||||
|
||||
@MyTest
|
||||
public void method2(){
|
||||
System.out.println("测试方法2执行了");
|
||||
}
|
||||
|
||||
@MyTest
|
||||
public void method3(){
|
||||
System.out.println("测试方法3执行了");
|
||||
}
|
||||
}
|
||||
29
javaSE-day12/src/com/inmind/annotation03/JunitTest10.java
Normal file
29
javaSE-day12/src/com/inmind/annotation03/JunitTest10.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.inmind.annotation03;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/*
|
||||
junit测试框架简单实现
|
||||
注解(自定义注解)+反射(识别注解+解析注解)
|
||||
|
||||
实现步骤:
|
||||
1.自定义注解 @MyTest
|
||||
2.反射获取所有的带有该注解的方法让他们执行
|
||||
*/
|
||||
public class JunitTest10 {
|
||||
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
|
||||
//获取测试类的Class对象
|
||||
Class<JunitDemo10> clazz = JunitDemo10.class;
|
||||
//获取JunitDemo10所有的方法
|
||||
Method[] methods = clazz.getMethods();
|
||||
System.out.println(methods.length);
|
||||
//遍历判断每个方法对象上是否有@MyTest注解
|
||||
for (Method method : methods) {
|
||||
boolean flag = method.isAnnotationPresent(MyTest.class);
|
||||
if (flag) {
|
||||
method.invoke(clazz.getConstructor().newInstance());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
11
javaSE-day12/src/com/inmind/annotation03/MyTest.java
Normal file
11
javaSE-day12/src/com/inmind/annotation03/MyTest.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.inmind.annotation03;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface MyTest {
|
||||
}
|
||||
Reference in New Issue
Block a user