一直好奇JUnit里面@Test的實(shí)現(xiàn),搜了不少網(wǎng)頁(yè),大部分都是講的使用方式,很少有人去講解實(shí)現(xiàn)原理。自己看源碼看了半天也沒(méi)有找到頭緒。
索性自己摸索著實(shí)現(xiàn)了一套類(lèi)似的效果,下一步準(zhǔn)備應(yīng)用在已經(jīng)完成的仿真測(cè)試上,雖然很初級(jí),但也算一個(gè)框架了。
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.
*/
//類(lèi)似junit的@Test效果
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Run {
//該操作發(fā)生的概率
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運(yùn)行完之后報(bào)告結(jié)果
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD})
public @interface Report {
}
這三個(gè)注解是對(duì)外提供的全部接口了。
2、測(cè)試類(lèi)
//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");
}
}