JUnit4.12 源码分析之TestClass

1. TestClass

// 源码:org.junit.runners.model.TestClass
// 该方法主要提供方法校验和注解搜索
public class TestClass implements Annotatable{
    private static final FieldComparator FIELD_COMPARATOR = new FieldComparator();
    private static final MethodComparator METHOD_COMPARATOR = new MethodComparator();

    // 三个成员变量
    private final Class<?> clazz;
    private final Map<Class<? extends Annotation>, List<FrameworkMethod>> methodsForAnnotations;
    private final Map<Class<? extends Annotation>, List<FrameworkField>> fieldsForAnnotations;

    // 由于JDK对标注的处理代价高昂,此处,构造器的作用是为了保证实例的共用
    public TestClass(Class<?> clazz){
        this.clazz = clazz;
        if(clazz != null && clazz.getConstructors().length > 1){
            throw new IllegalArgumentException(
                "Test class can only have one constructor");
        }

        Map<Class<? extends Annotation>, List<FrameworkMethod>> methodsForAnnotations =
            new LinkedHashMap<Class<? extends Annotation>, List<FrameworkMehod>>();
        Map<Class<? extends Annotation>, List<FrameworkField>> fieldsForAnnotations =
            new LinkedHashMap<Class<? extends Annotation>, List<FrameworkField>>();

        scanAnnotatedMembers(methodsForAnnotations, fieldsForAnnotations);

        this.methodsForAnnotations = makeDeeplyUnmodifiable(methodsForAnnotations);
        this.fieldsForAnnotations = makeDeeplyUnmodifiable(fieldsForAnnotations);
    }

    ...(略)
}


// 测试代码
public class TestUnit(){
    public TestUnit(){}

    @Test
    public void addx(int x){
        assertEquals(5, 1+x);
    }

    @Test
    public void add(){
        assertEquals(5.0, 4.0, 0.1);
    }

    @Test
    public void hello(){
        assertEquals(5.0, 4.0, 0.1);
    }
}


public class TestClassDemo{

    public static void main(String[] args) throws Throwable{
        TestClass kclass = new TestClass(TestUnit.class);
        System.out.println(kclass.getName());

        // Test.class 就是类中标明 @Test 注解的方法
        List<FrameworkMethod> list = kclass.getAnnotatedMethods(Test.class);
        for(FrameworkMethod fm : list){
            try{
                fm.invokeExplosively((TestUnit)kclass.getJavaClass().newInstance(), new Object[0]);
            }catch(Throwable e){
                System.out.println(e);
            }finally{
                System.out.println(fm.getName() + " invoked!");
            }
        }
    }
}

1222878-20180519090256245-127880787.png


参考资料:

转载于:https://www.cnblogs.com/linkworld/p/9059227.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值