我有带有@ExtendWith注释的自定义接口“平台”和实现ExecutionCondition的类。
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@ExtendWith(PlatformExecutionCondition.class)
public @interface Platform {
MobilePlatform[] value();
@Component
@RequiredArgsConstructor
public class PlatformExecutionCondition implements ExecutionCondition {
private final EmulatorConfigProperties emulatorConfigProperties;
private final PlatformAnnotationManager platformAnnotationManager;
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) {
MobilePlatform platform = MobilePlatform.getByName(emulatorConfigProperties.getPlatformName());
if (platform == null) {
return disabled("Mobile platform is not specified");
}
if (extensionContext.getTestMethod().isEmpty()) {
return enabled("Test class execution enabled");
}
Set<MobilePlatform> mobilePlatforms = platformAnnotationManager.getTestMobilePlatforms(extensionContext);
if (mobilePlatforms.contains(platform)) {
return enabled(format("{0} mobile platform is available for testing", platform.getName()));
} else {
return disabled(format("{0} mobile platform is not available for testing", platform.getName()));
}
}
}
运行测试时,我发现一个错误
java.lang.NoSuchMethodException: com.mob.market3b.platform.execution.PlatformExecutionCondition.
正如 @slaw 提到的,你的
PlatformExecutionCondition
必须有一个默认的无参数构造函数。
因此,
PlatformExecutionCondition
中的字段不能是final
。
尽管您可以在
PlatformExecutionCondition
中创建 ApplicationContext
的实例作为 Bean,并将其注入到测试类中用 @Autowired
和 @RegisterExtension
注释的字段中,但从 ApplicationContext
访问 Bean 的最简单方法
在自定义 JUnit Jupiter 扩展中,可以从 ApplicationContext
手动检索它们——例如通过 getBean(<bean type>)
。
您可以通过
PlatformExecutionCondition
访问 org.springframework.test.context.junit.jupiter.SpringExtension.getApplicationContext(ExtensionContext)
中的应用程序上下文。
另请参阅:https://stackoverflow.com/a/56922657/388980
请注意,通常不建议在
ApplicationContext
实现中访问 ExecutionCondition
(或应用程序上下文中的 beans),因为您的 ExecutionCondition
可能会有效地强制创建原本不会使用的 ApplicationContext
(如果 ExecutionCondition
最终禁用测试)。有关详细信息,请参阅 @DisabledIf(loadContext)
的文档。
Spring 的
@EnabledIf
和 @DisabledIf
注释可能是实现您自己的 ExecutionCondition
的更简单替代方案。