简体   繁体   中英

IntelliJ run context for JUnit TestTemplates

In JUnit 5 you can define your own test template and bind it to an annotation. Instead of @Test or @ParameterizedTest now I can use my own test annotaion @MyTest(...)

The problem is that Intellij does not recognize this annotation as JUnit test annotation thus does not give me the option to run/debug this test.

Can I extend this list of annotations that tells IntelliJ this is a test?

Picture on the left is a standard test where the context shows a run function. Picture on the right shows my template which works perfectly just the context does not recognize it as a test.

有上下文 上下文无法识别

My test template looks like this:

@Target(
    AnnotationTarget.ANNOTATION_CLASS,
    AnnotationTarget.FUNCTION
)
@Retention(AnnotationRetention.RUNTIME)
@Execution(ExecutionMode.CONCURRENT)
@TestTemplate
@ExtendWith(ScTestExtension::class)
annotation class ScTest(
 // ... some properties  
)



class ScTestExtension : TestTemplateInvocationContextProvider {

    override fun supportsTestTemplate(context: ExtensionContext): Boolean {
        return true
    }

    override fun provideTestTemplateInvocationContexts(extensionContext: ExtensionContext): Stream<TestTemplateInvocationContext> {
         // ... return invocation context
    }
}

Your ScTest.java should look similar to this one:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;

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

Derived from https://junit.org/junit5/docs/current/user-guide/#writing-tests-meta-annotations

IIRC, IDEA and other IDEs look for an instance of Testable to display the "Run..." icon. But normally, you shouldn't use that annotation directly. It should suffice to have it meta-annotated with @Test , @TestTemplate , or friends.

Here's another example using @TestTemplate that worked (at least, two years ago): CartesianProductTest.java

@TestTemplate
@ExtendWith(CartesianProductProvider.class)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CartesianProductTest {...}

Here is how "IntelliJ IDEA 2019.3 EAP (Community Edition) Build #IC-193.4386.10, built on October 9, 2019" shows the usage of the @CartesianProductTest annotation today:

在此处输入图像描述

Perhaps you need to switch to dark mode...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM