如何将此测试规则转换为Junit5?

发布于 2025-01-27 20:10:48 字数 1082 浏览 7 评论 0原文

我使用Junit4有一些自定义规则,我想将其转换为Junit5。但是,除了我应该使用junit5扩展而不是规则外,我还找不到有关迁移方法实现的良好文档。

public class MyRule implements MethodRule {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyRule.class);

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface MyAnnotation { }

    @Override
    public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
        Statement result = statement;
        if (hasMyAnnotation(frameworkMethod)) {
                result = new Statement() {
                    @Override
                    public void evaluate() {
                        LOGGER.info("Skipping test");
                    }
                };
            }
        }
        return result;
    }

    private static boolean hasMyAnnotation(final Annotatable frameworkMethod) {
        return frameworkMethod.getAnnotation(MyAnnotation.class) != null;
    }

我的课程使用Junit4 语句FrameworkMethod等,以找出我的方法是否具有注释...然后跳过它。我该如何转换?

I have some custom rule using junit4 which I would like to convert to junit5. However I'm not able to find good documentation on migrating a MethodRule implementation other than that I should be using junit5 extension instead of rule.

public class MyRule implements MethodRule {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyRule.class);

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface MyAnnotation { }

    @Override
    public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
        Statement result = statement;
        if (hasMyAnnotation(frameworkMethod)) {
                result = new Statement() {
                    @Override
                    public void evaluate() {
                        LOGGER.info("Skipping test");
                    }
                };
            }
        }
        return result;
    }

    private static boolean hasMyAnnotation(final Annotatable frameworkMethod) {
        return frameworkMethod.getAnnotation(MyAnnotation.class) != null;
    }

My class is using junit4 Statement, FrameworkMethod etc to find out if my method has an annotation... then to skip it. How can I convert this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

姜生凉生 2025-02-03 20:10:48

解决方案1,使用自定义注释禁用测试

Junit 5提供了一种可以控制是否应进行测试的扩展名。这是通过实现“ nofollow noreferrer”> experutionCondition 接口。

扩展实现:

import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.util.AnnotationUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;

public class SkipConditionExtension implements ExecutionCondition {
    private static final Logger LOGGER = LoggerFactory.getLogger(SkipConditionExtension.class);

    @Override
    public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
        AnnotatedElement element = context.getElement().orElse(null);

        if (hasMyAnnotation(element, MyAnnotation.class)) {
            LOGGER.info(() ->"Skipping test");
            return ConditionEvaluationResult.disabled(String.format("Skipped test: %s by @MyAnnotation", element));
        }

        return ConditionEvaluationResult.enabled("Test enabled");
    }

    private <T extends Annotation>  boolean hasMyAnnotation(final AnnotatedElement element, Class<T> annotation) {
        return element != null && AnnotationUtils.findAnnotation(element, annotation).isPresent();
    }
}

注册扩展:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(SkipConditionExtension.class)
public class TestObject {
    @Test
    public void test1() {

    }

    @Test
    @MyAnnotation
    public void test2() {

    }
}

输出:

INFO: Skipping test
Skipped test: public void com.test.TestObject.test2() by @MyAnnotation

解决方案2,通过Invocation Owterptor 跳过测试

nofollow noreferrer“> invocation interceptor”希望拦截测试电话的扩展。

当前实现将与您以前的 规则完全相同。

扩展实施:

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.util.AnnotationUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;

public class SkipCondition implements InvocationInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(SkipConditionExtension.class);

    @Override
    public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
        AnnotatedElement element = extensionContext.getElement().orElse(null);
        if (hasMyAnnotation(element, MyAnnotation.class)) {
            LOGGER.info(() ->"Skipping test");
            invocation.skip();
        } else {
            invocation.proceed();
        }
    }

    private <T extends Annotation>  boolean hasMyAnnotation(final AnnotatedElement element, Class<T> annotation) {
        return element != null && AnnotationUtils.findAnnotation(element, annotation).isPresent();
    }
}

注册扩展:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(SkipCondition.class)
public class TestObject {
    @Test
    public void test1() {

    }

    @Test
    @MyAnnotation
    public void test2() {

    }
}

请注意,您可以根据文档

Solution 1, Disable test with custom annotation

JUnit 5 provides a type of extension that can control whether or not a test should be run. This is defined by implementing the ExecutionCondition interface.

Extension implementation:

import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.util.AnnotationUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;

public class SkipConditionExtension implements ExecutionCondition {
    private static final Logger LOGGER = LoggerFactory.getLogger(SkipConditionExtension.class);

    @Override
    public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
        AnnotatedElement element = context.getElement().orElse(null);

        if (hasMyAnnotation(element, MyAnnotation.class)) {
            LOGGER.info(() ->"Skipping test");
            return ConditionEvaluationResult.disabled(String.format("Skipped test: %s by @MyAnnotation", element));
        }

        return ConditionEvaluationResult.enabled("Test enabled");
    }

    private <T extends Annotation>  boolean hasMyAnnotation(final AnnotatedElement element, Class<T> annotation) {
        return element != null && AnnotationUtils.findAnnotation(element, annotation).isPresent();
    }
}

Registring extenssion:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(SkipConditionExtension.class)
public class TestObject {
    @Test
    public void test1() {

    }

    @Test
    @MyAnnotation
    public void test2() {

    }
}

Output:

INFO: Skipping test
Skipped test: public void com.test.TestObject.test2() by @MyAnnotation

Solution 2, Skip test via invocation interseptor

InvocationInterceptor iterface defines the API for Extensions that wish to intercept calls to test.

Current implementation will behave exactly like your previous Rule.

Extension implementation:

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.junit.platform.commons.util.AnnotationUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;

public class SkipCondition implements InvocationInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(SkipConditionExtension.class);

    @Override
    public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
        AnnotatedElement element = extensionContext.getElement().orElse(null);
        if (hasMyAnnotation(element, MyAnnotation.class)) {
            LOGGER.info(() ->"Skipping test");
            invocation.skip();
        } else {
            invocation.proceed();
        }
    }

    private <T extends Annotation>  boolean hasMyAnnotation(final AnnotatedElement element, Class<T> annotation) {
        return element != null && AnnotationUtils.findAnnotation(element, annotation).isPresent();
    }
}

Registring extenssion:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(SkipCondition.class)
public class TestObject {
    @Test
    public void test1() {

    }

    @Test
    @MyAnnotation
    public void test2() {

    }
}

Please note, you can perform automatic extension registration according to documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文