MST

星途 面试题库

面试题:Java中JUnit如何使用自定义注解

请阐述在Java的JUnit测试框架中,如何自定义一个注解,并将其应用在测试方法上实现特定的功能,比如在测试方法执行前打印一些特定信息。请给出具体的代码示例,包括注解定义、使用该注解的测试类及方法。
30.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 定义自定义注解
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 "";
}
  1. 自定义测试规则类
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();
            }
        };
    }
}
  1. 使用注解的测试类及方法
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("测试方法执行中...");
    }
}