• 添加依赖

  新建一个maven项目,然后添加依赖:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <!-- 告诉该类库用于测试阶段 -->
  <scope>test</scope>
</dependency>
  • 接口
1 package cn.edu.xcu.reflect.dao;
2 public interface BookDao {
3   public void insert();
4   public void update();
5   public void del();
6 }
  • 实现类
import org.junit.Test;
import cn.edu.xcu.reflect.dao.BookDao;   //这么做存在代码重复   public class BookDaoImpl implements BookDao {   @Test//告诉 Junit 该方法要运行   @Override   public void insert() {   try {     System.out.println("开启会话");     ////     System.out.println("插入书籍");     ///     System.out.println("事务提交");   } catch (Exception e) {     System.out.println("事务回滚");   e.printStackTrace();     } finally {     System.out.println("关闭会话");   } }
  • 测试

      


  •  定义注解
@Retention(RetentionPolicy.RUNTIME) // 因为通过反射读取
@Target({ ElementType.METHOD }) // 测试方法
public @interface Test {
}
  • 在被测试类上添加注解
//这么做存在代码重复
public class BookDaoImpl implements BookDao {
  @Test
  @Override
  public void insert() {
    try {
    System.out.println("开启会话");
    ////
     System.out.println("插入书籍");
    ///
    System.out.println("事务提交");
      } catch (Exception e) {
    System.out.println("事务回滚");
    e.printStackTrace();
    } finally {
    System.out.println("关闭会话");
    }
  }
  @Override
  public void update() {
    try {
    System.out.println("开启会话");
    ////
    System.out.println("修改书籍");
    ///
    System.out.println("事务提交");
    } catch (Exception e) {
    System.out.println("事务回滚");
    e.printStackTrace();
    } finally {
    System.out.println("关闭会话");
}

}
  • 编写测试类工具
public class TestTool {
  public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
     startTest(BookDaoImpl.class);
}
public static void startTest(Class clazz)throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {   // 1 告诉测试那个类   Object obj = clazz.newInstance();   // 2 判断该类的方法是否有我们自定义的注解,如果有就调用该方法   Method[] ms = clazz.getDeclaredMethods();   for (Method method : ms) {   if (method.isAnnotationPresent(Test.class)) {   method.invoke(obj);       }     }   } }


02-12 10:08