当前位置: 首页 > 文档资料 > JUnit 5 用户指南 >

1.2.5.7 为测试模板提供调用上下文

优质
小牛编辑
132浏览
2023-12-01

ParameterResolver defines the Extension API for dynamically resolving parameters at runtime.

If a test class constructor, test method, or lifecycle method (see Test Classes and Methods) declares a parameter, the parameter must be resolved at runtime by a ParameterResolver. A ParameterResolver can either be built-in (see TestInfoParameterResolver) or registered by the user. Generally speaking, parameters may be resolved by name, type, annotation, or any combination thereof.

If you wish to implement a custom ParameterResolver that resolves parameters based solely on the type of the parameter, you may find it convenient to extend the TypeBasedParameterResolver which serves as a generic adapter for such use cases.

For concrete examples, consult the source code for CustomTypeParameterResolver, CustomAnnotationParameterResolver, and MapOfListsTypeBasedParameterResolver.

Due to a bug in the byte code generated by javac on JDK versions prior to JDK 9, looking up annotations on parameters directly via the core java.lang.reflect.Parameter API will always fail for inner class constructors (e.g., a constructor in a @Nested test class).

The ParameterContext API supplied to ParameterResolver implementations therefore includes the following convenience methods for correctly looking up annotations on parameters. Extension authors are strongly encouraged to use these methods instead of those provided in java.lang.reflect.Parameter in order to avoid this bug in the JDK.

  • boolean isAnnotated(Class<? extends Annotation> annotationType)
  • Optional<A> findAnnotation(Class<A> annotationType)
  • List<A> findRepeatableAnnotations(Class<A> annotationType)