JUnit Extension Registration
How-To register extensions via composed annotations, where it works, where it doesn't, and possible solutions
Basics of Composed Annotation Extension Registration (CAER)
public class SimpleExt implements BeforeEachCallback, AfterEachCallback {
public void beforeEach(final ExtensionContext context) {
Properties props = new Properties();
InputStream is = getClass().getResourceAsStream("/MyFile.props");
props.load(is);
System.setProperties(props);
}
public void afterEach(final ExtensionContext context) {
// reset the sys props ...
}
}@Target({ TYPE, METHOD, ANNOTATION_TYPE }) @Retention(RUNTIME)
@ExtendWith(SimpleExt.class) // Just one extension registered, but it could be several
public @interface SimpleAnn { }Adding Configuration to an extension registered via CAER
The two findAnnotation methods
findAnnotation methodsAnnotationSupport.findAnnotation(Optional<AnnotatedElement>, Class<A>) AKA Method 1
AnnotationSupport.findAnnotation(Optional<AnnotatedElement>, Class<A>) AKA Method 1AnnotationSupport.findAnnotation(Class<?>, Class<A>, SearchOption) AKA Method 2
AnnotationSupport.findAnnotation(Class<?>, Class<A>, SearchOption) AKA Method 2Method
Finds superclass ann. if marked as inherited
Finds superclass ann. if NOT marked as inherited
Finds ann. on parent of @Nested class
Is well supported
Was the annotation on a method or class?
Determining which class was the annotated class
Possible Solutions for Developers using CAER
Option 1: Use Method 1 + @Inherited
The Pros
The Cons
Option 2: Use the Method 2 + @Inherited
The Pros
The Cons
Option 3: Reimplement the needed findAnnotation methods as part of your distributable
findAnnotation methods as part of your distributableThe Pros
The Cons
Option 4: Separate your extensions into class level and method level.
Other ideas?
Last updated