- 定义自定义注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomTestAnnotation {
String value() default "";
}
- 自定义测试规则类:
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class CustomTestRule implements TestRule {
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
CustomTestAnnotation annotation = description.getAnnotation(CustomTestAnnotation.class);
if (annotation != null) {
System.out.println("执行测试方法前打印特定信息: " + annotation.value());
}
base.evaluate();
}
};
}
}
- 使用注解的测试类及方法:
import org.junit.Rule;
import org.junit.Test;
public class CustomAnnotationTest {
@Rule
public CustomTestRule customTestRule = new CustomTestRule();
@Test
@CustomTestAnnotation("这是一个自定义注解测试")
public void testMethod() {
System.out.println("测试方法执行中...");
}
}