简体   繁体   中英

How to create JUnit5 custom extension that could be applied only on test methods and not on the entire test class

I want to create a JUnit5 extension that will resolve a test method parameters, implementing ParameterResolver :

public class MyParameterResolver implements ParameterResolver {

    @Override
    public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
        ...
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
        ...
    }
}

The extension is meant to use only on top of test methods:

public class DemoTest {

    @Test
    @ExtendWith(MyParameterResolver.class)
    public void test(int x, int y) {
        ...
    }

    @Test
    @ExtendWith(MyParameterResolver.class)
    public void test2(int x, int y) {
        ...
    }
} 

How can I prevent it from being used on top of the test class (preferably at compile time if possible, but runtime would be good either)?

//I don't want this to work
@ExtendWith(MyParameterResolver.class)
public class DemoTest {
    ...
} 

To check at compile time:

If you look at @ExtendWith source code, you will see it is a composite annotation and there is a @Target({ElementType.TYPE, ElementType.METHOD}) . If this was just @ElementType.METHOD , it will do exactly what you want and not permit @ExtendWith on a class.

Changing the @ExtendWith however, is not a good option - you do not own it and you want to be able to use it everywhere :)

What you can do is create your own composite annotation:

@Target(value = {ElementType.METHOD})
@ExtendWith(MyParameterResolver.class)
public @interface MyParameterResolverAnnotation {
}

You can now use that instead of @ExtendWith(MyParameterResolver.class) and it will not compile if put on a class.

I cannot think about another way to prevent this from happening at compile time.

At runtime/build time you have more options, like setting a custom checkstyle rule that will break the build in case it finds @ExtendWith(MyParameterResolver.class) on a class.

You can even combine both of the approaches.

Hope that helps!

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