没有显式配置的 SpringExtension?

SpringExtension without an explicit configuration?

我用 SpringExtension 进行了 JUnit5 测试。我只需要通过 Spring 的 @Value:

注入环境变量
@ExtendWith(SpringExtension.class)
class MyTest {
    @Value("${myValue}") String myValue;
    ...

这样做时,我收到一条错误消息:

Failed to load ApplicationContext Caused by: java.lang.IllegalStateException: Neither GenericGroovyXmlContextLoader nor AnnotationConfigContextLoader was able to load an ApplicationContext

当然Spring需要有context的配置,所以我把它放到了测试代码中:

@ExtendWith(SpringExtension.class)
@ContextConfiguration
class MyTest {
    @Value("${myValue}") String myValue;

    @Configuration
    static class TestConfig { /*empty*/ }
    ...

虽然这可行,但对我来说它看起来像很多不必要的样板代码。有没有更简单的方法?

更新

一个较短的变体是使用 @SpringJUnitConfig,它使 @ContextConfiguration@ExtendWith(SpringExtension.class) 开箱即用。

但是还是需要一个配置class(即使是空的)。

In SpringBoot to 运行 a spring application context,你需要在测试中使用@SpringBootTest annotation class:

@ExtendWith(SpringExtension.class)
@SpringBootTest
class MyTest {
    @Value("${myValue}") String myValue;
    ...

更新:

或者如果您只使用 Spring 框架(没有 spring 引导),那么测试配置取决于您使用的 spring 框架的版本,以及 spring 配置你的项目。

你可以通过使用@ContextConfiguration 来设置配置文件,如果你使用java config 那么它将是这样的:

@ContextConfiguration(classes = AppConfig.class)
@ExtendWith(SpringExtension.class)
class MyTest {
    ...

或者如果您使用 xml 配置:

@ContextConfiguration("/test-config.xml")
@ExtendWith(SpringExtension.class)
class MyTest {
    ...

这两者都取决于您的项目配置结构和测试中需要的 bean 列表。

有关上下文配置的更多详细信息:https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#spring-testing-annotation-contextconfiguration

如果您使用早于 5.0 的 Spring 框架,那么您会发现这个库很有用:https://github.com/sbrannen/spring-test-junit5

您不能 运行 没有配置的基于 Spring 的测试。 Spring 测试上下文框架 (TCF) expects/requires 和 ApplicationContext。要创建 ApplicationContext,需要存在表单配置 (xml、Java)。

您有 2 个选项可以让它发挥作用

  1. 使用空配置,emtpy XML 文件或空 @Configuration class
  2. 编写自定义 ContextLoader 创建一个空的应用程序上下文。

选项 1 可能是最容易实现的。您可以创建一个全局空配置并从 @ContextConfiguration 中引用它。

正如其他答案和评论中所指出的,您需要指定一个空的配置源,特别是 @Configuration class、XML 配置文件、Groovy 配置文件,或 ApplicationContextInitializer.

最简单的方法是创建您自己的组合注释,预定义空配置。

如果你在你的项目中引入下面的@EmptySpringJUnitConfig注释,你可以在任何你想要一个空SpringApplicationContext的地方使用它(而不是@SpringJUnitConfig)。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Inherited
@SpringJUnitConfig(EmptySpringJUnitConfig.Config.class)
public @interface EmptySpringJUnitConfig {
    @Configuration
    class Config {
    }
}