SpringExtension没有显式配置?

时间:2019-06-18 06:44:42

标签: java spring spring-test

我有一个SpringExtension的JUnit5测试。我需要的只是通过Spring的@Value注入的环境变量:

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

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

  

无法加载ApplicationContext,原因是:   java.lang.IllegalStateException:GenericGroovyXmlContextLoader和AnnotationConfigContextLoader均无法加载ApplicationContext

当然,Spring需要进行上下文配置,因此我将其放入测试代码中:

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

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

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

更新

一个更短的变体是使用@SpringJUnitConfig,它可以同时使用@ContextConfiguration@ExtendWith(SpringExtension.class)

但是仍然需要一个配置类(甚至是一个空的类)。

3 个答案:

答案 0 :(得分:2)

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

最简单的方法是创建自己的组成的注释,该注释会预先定义空配置。

如果在项目中引入以下@EmptySpringJUnitConfig注释,则可以在任何需要空Spring @SpringJUnitConfig的地方使用它(而不是ApplicationContext)。

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

答案 1 :(得分:1)

没有配置就无法运行基于Spring的测试。春季测试上下文框架(TCF)期望/需要一个ApplicationContext。要创建ApplicationContext,需要提供表单配置(xml,Java)。

您有2种选择可以使其正常工作

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

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

答案 2 :(得分:0)

在SpringBoot中运行spring应用程序上下文,您需要在测试类上使用@SpringBootTest批注:

@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 Framework,则可以找到有用的该库:https://github.com/sbrannen/spring-test-junit5

相关问题