java自定义@Test注解

相信用过 Junit 的朋友都知道 JUnit是Java的一个单元测试框架,在实现自动单元测试的情况下可以大大的提高开发的效率,那么我们如何自定义一个@Test注解呢?

首先,我们先写一个@Test注解,如下:

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Woo_home
 * @create by 2019/9/18
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
}

@Test注解类型的声明就是它自身通过Retention和Target注解进行了注解。注解类型声明中的这种注解被称为元注解(meta-annotation)。@Retention(RetentionPolicy.RUNTIME)元注解表明,@Test注解应该在运行时保留。如果没有保留,测试工具就无法知道@Test注解。@Target(ElementType.METHOD)元注解表明,@Test注解只在方法声明中才是合法的:它不能运用到类声明。域声明或者其他程序元素上

在应用中使用@Test注解

package demo;

import annotation.Test;

/**
 * @author Woo_home
 * @create by 2019/9/18
 */
public class TestDemo {

    @Test
    public void hello(){
        System.out.println("Hello World");
    }

}

编写测试运行类

package utils;

import annotation.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Woo_home
 * @create by 2019/9/18
 */
public class RunTests {
    public static void main(String[] args) throws Exception{
        int tests = 0; //记录成功
        int passed = 0;//记录失败
        Class testClass = Class.forName("demo.TestDemo"); //反射带有@Test注解的类
        for (Method m : testClass.getDeclaredMethods()) {
            if (m.isAnnotationPresent(Test.class)){ //Test是定义的注解类,isAnnotationPresent方法告知该工具运行哪些方法
                tests++;
                try {
                    m.invoke(testClass.newInstance()); //通过调用invoke反射式地运行类中所有标注了@Test的方法
                    passed++;
                }catch (InvocationTargetException wrappedExc){
                    Throwable exc = wrappedExc.getCause();
                    System.out.println(m + " failed: " + exc);
                }catch (Exception exc){
                    System.out.println("INVALID @Test: " + m);
                }
            }
        }
        System.out.printf("Passed: %d, Failed: %d%n",tests,tests-passed);
    }
}

我们运行这个类就会打印出标注有@Test注解的方法

但是标注有@Test的类只能用于没有返回值的方法,如果用了有返回值的方法就会报错
,比如:

package demo;

import annotation.Test;

/**
 * @author Woo_home
 * @create by 2019/9/18
 */
public class TestDemo {

    @Test
    public int test1(int i){
        i = 0;
        return i;
    }

    @Test
    public void hello(){
        System.out.println("Hello World");
    }

}

运行测试运行类后会有一个失败
在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值