一直好奇JUnit里面@Test的实现,搜了不少网页,大部分都是讲的使用方式,很少有人去讲解实现原理。自己看源码看了半天也没有找到头绪。
索性自己摸索着实现了一套类似的效果,下一步准备应用在已经完成的仿真测试上,虽然很初级,但也算一个框架了。
1、定义注解
//Simulation.java
package com.sigh.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by sigh on 2015/6/10.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE})
public @interface Simulation {
}
//Run.java
package com.sigh.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by sigh on 2015/6/10.
*/
//类似junit的@Test效果
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Run {
//该操作发生的概率
double rate() default 0;
}
//Report.java
package com.sigh.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by sigh on 2015/6/10.
*/
//在所有@Run运行完之后报告结果
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
public @interface Report {
}
这三个注解是对外提供的全部接口了。
2、测试类
//First.java
package com.sigh.test;
import org.springframework.stereotype.Service;
/**
* Created by sigh on 2015/6/9.
*/
@Simulation
@Service
public class First {
@Run(rate = 0.5)
boolean run() {
System.out.println("first");
return true;
}
@Report
void report() {
System.out.println("report first");
}
}
//Second.java
package com.sigh.test;
import org.springframework.stereotype.Service;
/**
* Created by sigh on 2015/6/9.
*/
@Simulation
@Service
public class Second {
@Run(rate = 0.5)
long doWork() {
System.out.println("second");
return 3;
}
@Report
void display() {
System.out.println("display second");
}
}